4

i am using the preinstalled package RScript in R.

I want to call the following R-Script with the name 'test.R' from the command prompt:

a <- c("a", "b", "c")
a

args <- commandArgs(TRUE)
b <- as.vector(args[1])
b

I use the following command:

RScript test.R c("d","e","f")

This creates following output:

[1] "a" "b" "c"
[1] "c(d,e,f)"

As you see, the first (and only) argument is interpreted as a String, then converted to a 1-dimensional vector. How can the argument be interpreted as a vector?

Sidenote: Of course the items of the vector could be separated into several arguments, but in my final project, there will be more than one vector-argument. And to implement something like this is my last resort:

RScript test.R "d" "e" "f" END_OF_VECTOR_1 "g" "h" "i" END_OF_VECTOR_2 "j" "k" "l"
4

3 回答 3

4

您可以使用逗号分隔的列表。

在命令行上:

RScript test.R a,b,c d,e,f g,h,i j

在您的代码中:

vargs <- strsplit(args, ",")
vargs
# [[1]]
# [1] "a" "b" "c"
# 
# [[2]]
# [1] "d" "e" "f"
# 
# [[3]]
# [1] "g" "h" "i"
# 
# [[4]]
# [1] "j"
于 2014-11-01T20:11:45.097 回答
1

您可以使用以下方法清理以下内容a = "c(1,2,3)"

as.numeric(unlist(strsplit(substr(a,3,nchar(a)-1), ",")))

只要脚本始终传递一个格式正确的字符串,并且您知道预期的格式,它就可以正常工作。在 RScript 参数中,c()不应该列出该部分,只需给它一个带引号的逗号分隔列表。

于 2016-04-01T16:48:27.093 回答
-1

@flodel 感谢您的回答,这是一种方法。除此之外,我找到了解决我的问题的方法。

文件“test.R”中的以下代码将参数存储在“args”中。然后将 'args' 中的文本评估为正常的 R 表达式,并作为输出,给出 a 和 b。

args <- commandArgs(TRUE)
eval(parse(text=args))
a
b

代码可以在命令提示符下调用如下:

RScript test.R a=5 b=as.vector(c('foo', 'bar'))
于 2014-11-01T22:47:57.720 回答