[英]read command line arguments as list in R script
如何以列表形式读取R中的命令行参数?
例如:Rscript myScript.R你好世界
myScript.R代码:
args <- commandArgs(trailingOnly =TRUE)
print(typeof(args)) ---> character
print(args[1]) ---> hello
print(args[2]) ---> world
如果我能够访问上述的第1和第2个元素,那么为什么typeof args是character而不为什么列出?
另外,如果它是一个字符,我如何将其读为第一个元素是hello而第二个元素是world的命名列表。
如果args是一个字符,那么我尝试将其按空格分割以形成一个列表:
args <- strsplit(args , " ")
但是它创建列表列表。 请帮忙。
好吧,我想我知道了...
args
实际上是由两个元素组成的character
向量。 因此,可以分别使用args[1]
和args[2]
来访问'hello'
和'world'
是完全正常的。
现在,我不明白您为什么要将其作为列表...但是,如果您确实希望将其作为列表...也许您应该这样做:
args <- commandArgs(trailingOnly =TRUE)
print(typeof(args))
print(args[1]) # 'hello'
print(args[2]) # 'world'
args_names <- args # saving 'hello' and 'world' to be the names of the list
args <- as.list(args) # making the list
names(args) <- args_names # naming the list
print(typeof(args)) # showing that it is now a list
这就是你想要的吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.