在终端中打印函数的输出

Print the output of a function in terminal

我在 R 中定义了以下函数。

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

当我在 R 控制台中输入 fahr_to_kelvin(32) 时,它 returns 273.15(没有打印“Hello World”!我不知道为什么!)无论如何,我尝试在下面编写代码:

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

但是,终端中没有显示任何内容(没有错误)。你能帮我看看为什么它不起作用吗?

问题是脚本文件只包含函数的声明,没有实际调用。

在脚本末尾添加一个新行以调用该函数,或者更好地从命令行读取参数:

#!/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