mdslt
mdslt

Reputation: 203

Print the output of a function in terminal

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?

Upvotes: 0

Views: 603

Answers (1)

lrv
lrv

Reputation: 290

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

Upvotes: 2

Related Questions