【问题标题】:Print the output of a function in terminal在终端中打印函数的输出
【发布时间】:2021-01-03 23:13:49
【问题描述】:

我在 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) 时,它返回 273.15(没有打印“Hello World”!我不知道为什么!)无论如何,我尝试在下面编写代码:

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

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

【问题讨论】:

    标签: r linux function terminal output


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢。当我在终端中调用此函数时,这有效。但是,当我从 R 控制台调用它时,我遇到了一个错误(“找不到函数”)。这可能是什么原因?
    • 在控制台中启动新的 R 会话时,需要先加载函数的定义。你可以通过调用&gt; source("~/tuning1/Fun1.R")
    • 非常感谢。你说的对。有没有机会好好看看这个问题? link
    猜你喜欢
    • 2020-02-24
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    相关资源
    最近更新 更多