Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]")
like image 795
biocyberman Avatar asked Jun 08 '15 13:06

biocyberman


People also ask

What is string interpolation better known as?

String interpolation is a technique that enables you to insert expression values into literal strings. It is also known as variable substitution, variable interpolation, or variable expansion. It is a process of evaluating string literals containing one or more placeholders that get replaced by corresponding values.

Which character should be used for string interpolation?

To identify a string literal as an interpolated string, prepend it with the $ symbol. You can't have any white space between the $ and the " that starts a string literal.

Why string interpolation is useful?

The string interpolation is a great feature because it helps to insert values into string literals in a concise and readable manner.

What is swift interpolation?

String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal. You can use string interpolation in both single-line and multiline string literals.


2 Answers

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

name="Foo Bar"
glue::glue("How do you do, {name}?")
like image 178
Holger Brandl Avatar answered Sep 29 '22 02:09

Holger Brandl


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"
like image 42
Uwe Avatar answered Sep 29 '22 02:09

Uwe