简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM