0

I have defined the following function in R.

#!/usr/bin/Rscript
fahr_to_kelvin <- function(temp) {
  kelvin <- ((temp - 32) * (5 / 9)) + 273.15
  print("Hello World")
  return(kelvin)
}

When I enter fahr_to_kelvin(32) in the R console, it returns 273.15 (without printing "Hello World"! I do not know why!) Anyway, I try to code below:

chmod +x ~/tuning1/Fun1.R
~/tuning1/Fun1.R

However, nothing appears in the terminal (with no error). Would you please help me why it is not working?

1 Answer 1

2

The problem is that the script file only contains the declaration of the function, without the actual invocation.

Add a new line to the end of the script to invoke the function, or better read the argument from command line:

#!/usr/bin/Rscript
fahr_to_kelvin <- function(temp) {
  kelvin <- ((temp - 32) * (5 / 9)) + 273.15
  print("Hello World")
  return(kelvin)
}

args <- commandArgs(trailingOnly=TRUE)
if (length(args) > 0) {
  fahr_to_kelvin(as.numeric(args[1]))
} else {
   print("Supply one argument as the numeric value: usage ./Fun1 temp")
}

$ Rscript Fun1.R 32 
[1] "Hello World"
[1] 273.15
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. That works when I call this function in the terminal. However, when I call it from the R console, I face an error ("cannot find the function"). What could be the reason of this?
When you start a new R session in the console, you need to load the definition of the function first. You can do this by calling > source("~/tuning1/Fun1.R")
Thank you so much. You are right. Have had any chance to kindly look at this question? link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.