Better string interpolation in R

I need to create long command lines in Rand pass them to system(). It is very inconvenient for me to use the function paste0/pasteor even sprintfto build each command line. Is there an easier way to do this:

Instead of these 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 do it:

cmd <- buildcommand("command -a %line$elem1 -b %line$elem3 -f %df$Colum5[4]")
+7
source share
6 answers

This is very close to what you are asking:

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

Here is an example of self-sufficient reproducible:

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"
+6
source

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

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

1.1.0 ( CRAN 2016-08-19) 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"
+9

Another option is to use whisker.renderfrom https://github.com/edwindj/whisker , which is an {{Mustache}} implementation in R. Example of use

require(dplyr); require(whisker)

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

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

0
source
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

-1
source

All Articles