【问题标题】:Character vector as an argument to R script字符向量作为 R 脚本的参数
【发布时间】:2012-12-12 12:50:38
【问题描述】:

我正在运行 R 脚本,但遇到错误:

Rscript 例子.R "a,b,c"

我在上面运行代码,其中 a、b、c 是作为参数传递的字符向量的元素。如果我传递数值(例如 1,5,6),上面的代码可以正常工作

Code is :
library("optparse")
library("tldutils") # eval_string
# install.packages("tldutils", repos="http://R-Forge.R-project.org")
option_list <- list(
make_option(c("-c", "--count"), type="character", default="5",
help='Vector of numbers separated by commas and surrounded by ""',
metavar="number")
)
args <- parse_args(OptionParser(option_list = option_list))
print(args$c)
eval_string(sprintf("foo = c(%s)", args$c))
print(foo)

错误是:

Error in eval(expr, envir, enclos) : object 'a' not found
Calls: eval_string -> eval.parent -> eval -> eval
Execution halted

请帮帮我,我需要在哪里编辑代码?

【问题讨论】:

    标签: r


    【解决方案1】:

    不确定我是否得到了你所追求的,但我希望你能够自己弄清楚细节并解决你的问题。

    将字符向量作为参数传递给 R 的最简单方法是使用 commandArgs 函数(基本包的,无需安装任何花哨的东西)。

    # Start R from the shell
    $ R --args a,b,c
    
    # Within R
    > commandArgs()
    [1] "/usr/lib64/R/bin/exec/R" "--args"                 
    [3] "a,b,c"
    

    如果您只想获取--args 之后指定的参数,请使用trailingOnly=TRUE。添加strsplit"a,b,c" 转换为三元素向量。或者,将逗号更改为空格,您不需要strsplit

    $ R --args a,b,c
    ...
    > strsplit(commandArgs(TRUE), ",")[[1]]
    [1] "a" "b" "c"
    
    $ R --args a b c
    ...
    > commandArgs(T)
    [1] "a" "b" "c"
    

    【讨论】:

      【解决方案2】:

      您传递给脚本的“a,b,c”被解释为变量名,而不是字符串。

      编辑:无论如何,我不明白您为什么要将数据作为参数而不是 a) 从标准输入中读取 或更好 b)使用例如read.table从文件中读取它

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-01
        • 2018-11-28
        相关资源
        最近更新 更多