【问题标题】:Manipulate string from command line argument从命令行参数操作字符串
【发布时间】:2021-12-04 08:56:35
【问题描述】:

我正在使用 optparse 调用一个参数,但我需要结果参数的字符串(变量 x)的格式为 "test", "test2", "test3"(引号用逗号分隔):

# Set up command line arguments 

library("optparse")

option_list = list(
  make_option(c("--test"), type="character", default=NULL, 
              help="test", metavar="character")

opt_parser = OptionParser(option_list=option_list);
opt = parse_args(opt_parser);

# grab argument into x variable

x <- (opt$pathcsv)
print(x)

进入命令行:

Rscript --vanilla riboeclip_ma.R --pathcsv="test test2 test3"

输出是字符类型:

"test test2 test3"

但是,我希望 x 变量的格式为 "test", "test2", "test3"

我的代码是这样设置的(注意我在向量中有"test", "test2", "test3"):

all_counts.poly.colData <-
   data.frame(Condition =
                c("test", "test2", "test3"))

但是,我想传递那个 x 变量来实现相同的结果(我正在尝试自动化这个过程)。

all_counts.poly.colData <-
   data.frame(Condition =
                c(x))

如果有更好的方法可以做到这一点,请告诉我,因为我还是 R 新手,昨天开始使用命令行参数。

【问题讨论】:

    标签: r string


    【解决方案1】:

    使用基数 R 中的splitstr 将其拆分为向量:

    strsplit(opt$pathcsv, " ")[[1]]
    

    如果要添加逗号,可以使用gsub:

    gsub(" ", ", ", opt$pathcsv)
    [1] "test, test2, test3"
    

    如果您想要文字引号,请使用 dQuote 应用于每个引号,然后将其粘贴在一起:

    paste(sapply(strsplit(opt$pathcsv, " ")[[1]], dQuote), collapse = ",")
    [1] "“test”,“test2”,“test3”"
    

    根据您的问题,您应该使用 strsplit 来复制您硬编码的内容:

    data.frame(Condition =
                    c("test1", "test2", "test3"))
      Condition
    1      test
    2     test2
    3     test3
    
    x <- strsplit(opt$pathcsv, " ")[[1]]
    
    data.frame(Condition = x)
     Condition
    1      test
    2     test2
    3     test3
    

    c("test", "test1", "test2") 是一个字符向量,您不应该尝试通过添加引号和逗号来复制创建字符向量的语法。相反,将您的命令行参数直接解析为字符向量:

    all(strsplit(opt$pathcsv, " ")[[1]] == c("test", "test2", "test3"))
    [1] TRUE
    

    【讨论】:

    • 是否有模拟“test1”、“test2”、“test3”的方法?
    • 你是说你想要一个像""test1", "test2", "test3""这样的角色对象吗?
    • 我只需要解析参数的字符串是用逗号分隔的引号。 “test1”、“test2”、“test3”
    • @fewidiy651 正如我在帖子中提到的,不要尝试复制您的硬代码。相反,您可以将参数直接解析为向量,这样就可以了。
    猜你喜欢
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    相关资源
    最近更新 更多