字符之间添加逗号

  • 本文关键字:添加 之间 字符 r
  • 更新时间 :
  • 英文 :


我用optparse调用一个参数,但我需要得到的参数(变量x)的格式如下所示:

# 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"而不影响命令行参数的给出。

您可以将x值拆分为空白和unlist,以获得字符串向量。

x <- (opt$pathcsv)
#x <- "test test2 test3"
x1 <- unlist(strsplit(x, '\s+'))
x2 <- paste0(sprintf('"%s"', x1), collapse = ',')
x2
#[1] ""test","test2","test3""

当显示R转义引号时,cat可以查看真实字符串。

cat(x2)
#"test","test2","test3"

我们也可以做

toString(dQuote(strsplit(x, "\s+")[[1]], FALSE))
[1] ""test", "test2", "test3""

数据
x <- (opt$pathcsv)
x <- "test test2 test3"