【问题标题】:read command line arguments as list in R script将命令行参数读取为 R 脚本中的列表
【发布时间】:2017-12-16 04:55:50
【问题描述】:

如何以列表的形式读取 R 中的命令行参数?

例如:Rscript myScript.R hello world

myScript.R 代码:

args <- commandArgs(trailingOnly =TRUE)
print(typeof(args)) ---> character
print(args[1])      ---> hello
print(args[2])      ---> world

如果我能够像上面那样访问第一个和第二个元素,那么为什么 typeof args 是字符,为什么不列出呢?

另外,如果它是一个字符,我如何将其读取为一个命名列表,其第一个元素是 hello,第二个元素是 world。

如果 args 是一个字符,那么我尝试将其按空格拆分以形成一个列表:

args <- strsplit(args , " ")

但它会创建列表列表。请帮忙。

【问题讨论】:

    标签: arrays r list vector command-line


    【解决方案1】:

    好吧,我想我想通了……

    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
    

    这是你想要的吗?

    【讨论】:

    • 什么时候做:print(typeof(args_[1])) print(typeof(args[2]))。它将显示列表。但是元素应该是字符,参数应该是列表
    • 那是因为你使用了错误的索引方式。要获取字符元素,您应该使用args[[1]] 或args[[2]],因为它们是列表的元素。如果您使用args[1] 或args[2],则返回的值也是列表。这是列表的正常行为。 args 已经是一个列表。
    猜你喜欢
    • 2017-03-16
    • 2013-10-22
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    相关资源
    最近更新 更多