better string interpolation in R

心已入冬 提交于 2019-12-10 13:04:54

问题


I need to build up long command lines in R and pass them to system(). I find it is very inconvenient to use paste0/paste function, or even sprintf function to build each command line. Is there a simpler way to do like this:

Instead of this hard-to-read-and-too-many-quotes:

cmd <- paste("command", "-a", line$elem1, "-b", line$elem3, "-f", df$Colum5[4])

or:

cmd <- sprintf("command -a %s -b %s -f %s", line$elem1, line$elem3, df$Colum5[4])

Can I have this:

cmd <- buildcommand("command -a %line$elem1 -b %line$elem3 -f %df$Colum5[4]")

回答1:


This comes pretty close to what you are asking for:

library(gsubfn)
cmd <- fn$identity("command -a `line$elem1` -b `line$elem3` -f `df$Colum5[4]`")

Here is a self contained reproducible example:

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]`")

giving:

> cmd
[1] "command -a 10 -b 30 -f 4"



回答2:


For a tidyverse solution see https://github.com/tidyverse/glue. Example

name="Foo Bar"
glue::glue("How do you do, {name}?")



回答3:


With version 1.1.0 (CRAN release on 2016-08-19), the stringr package has gained a string interpolation function str_interp() which is an alternative to the gsubfn package.

# 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"



回答4:


Another option would be to use whisker.render from https://github.com/edwindj/whisker which is a {{Mustache}} implementation in R. Usage example:

require(dplyr); require(whisker)

bedFile="test.bed"
whisker.render("processing {{bedFile}}") %>% print



回答5:


Not really a string interpolation solution, but still a very good option for the problem is to use the processx package instead of system() and then you don't need to quote anything.




回答6:


library(GetoptLong)

str = qq("region = (@{region[1]}, @{region[2]}), value = @{value}, name = '@{name}'")
cat(str)

qqcat("region = (@{region[1]}, @{region[2]}), value = @{value}, name = '@{name}'")

https://cran.r-project.org/web/packages/GetoptLong/vignettes/variable_interpolation.html



来源:https://stackoverflow.com/questions/30711019/better-string-interpolation-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!