bio*_*man 8 r string-interpolation
我需要建立长命令行R并将它们传递给system().我发现使用paste0/paste函数甚至sprintf函数构建每个命令行都非常不方便.是否有更简单的方法:
而不是这个难以阅读和太多的报价:
cmd <- paste("command", "-a", line$elem1, "-b", line$elem3, "-f", df$Colum5[4])
Run Code Online (Sandbox Code Playgroud)
要么:
cmd <- sprintf("command -a %s -b %s -f %s", line$elem1, line$elem3, df$Colum5[4])
Run Code Online (Sandbox Code Playgroud)
我想要这个,可以吗:
cmd <- buildcommand("command -a %line$elem1 -b %line$elem3 -f %df$Colum5[4]")
Run Code Online (Sandbox Code Playgroud)
Hol*_*ndl 35
有关整数解决方案,请参阅https://github.com/tidyverse/glue.例
name="Foo Bar"
glue::glue("How do you do, {name}?")
Run Code Online (Sandbox Code Playgroud)
对于版本1.1.0(2016-08-19上的CRAN版本),该stringr软件包已获得字符串插值功能str_interp(),该功能可替代该gsubfn软件包.
# sample data
line <- list(elem1 = 10, elem3 = 30)
df <- data.frame(Colum5 = 1:4)
# do the string interpolation
stringr::str_interp("command -a ${line$elem1} -b ${line$elem3} -f ${df$Colum5[4]}")
#[1] "command -a 10 -b 30 -f 4"
Run Code Online (Sandbox Code Playgroud)
这非常接近您的要求:
library(gsubfn)
cmd <- fn$identity("command -a `line$elem1` -b `line$elem3` -f `df$Colum5[4]`")
Run Code Online (Sandbox Code Playgroud)
这是一个自包含的可重现的例子:
library(gsubfn)
line <- list(elem1 = 10, elem3 = 30)
df <- data.frame(Colum5 = 1:4)
cmd <- fn$identity("command -a `line$elem1` -b `line$elem3` -f `df$Colum5[4]`")
Run Code Online (Sandbox Code Playgroud)
赠送:
> cmd
[1] "command -a 10 -b 30 -f 4"
Run Code Online (Sandbox Code Playgroud)