biocyberman biocyberman -4 years ago 97
R Question

better string interpolation in R

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

Answer Source

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"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download