Reputation: 1075
Does R have an equivalent of the Python f-string? Like this example in Python:
name = "Eric"
age = 42
f"Hello, {name}. You are {age}."
I know about paste
and paste0
, but they require you to separate the different elements with commas. I could not find anything about it while searching the Internet.
Upvotes: 39
Views: 29214
Reputation: 1335
sprintf is the most direct option in R's standard library, so you don't need to install any other packages or libraries since it's just a wrapper for the underlying C function. However, I will admit the syntax is a bit trickier if you aren't used to it.
name <- "Eric"
age <- 42
sprintf("Hello, %s. You are %s.", name, age)
Result:
[1] "Hello, Eric. You are 42."
If you really don't like the syntax there, you can try paste0 to get the same result.
name <- "Eric"
age <- 42
paste0("Hello, ", name, ". You are ", age, ".")
Upvotes: 25
Reputation: 270010
The gsubfn package allows you to preface any function with fn$
in which case character arguments will support perl-style string interpolation using backticks or $ sign (and formula notation can be used for function arguments).
library(gsubfn)
name <- "Eric"
age <- 42
fn$plot(0, main = "Hello, `name`. You are `age`.")
The part within backticks can be an R expression:
fn$identity("Hello, `name`. You are `age+1`.")
## [1] "Hello, Eric. You are 43."
It also supports $ notation if the end of the variable name can be inferred from the string. That is not the case in the above since dot is valid in a variable name but this would work:
fn$c("Hello $name")
## [1] "Hello Eric"
One can also use gsubfn from the same package. This looks for a string surrounded by brace brackets and then substitutes the variable name in it for its contents.
gsubfn("{(.*?)}", get, "Hello, {name}. You are {age}.")
## [1] "Hello, Eric. You are 42."
or a list can be provided as the second argument
L <- list(name = "Eric", age = 42)
gsubfn("{(.*?)}", L, "Hello, {name}. You are {age}.")
## [1] "Hello, Eric. You are 42."
This would also work using the same list. It avoids the use of {...} and would work as long as name and age do not appear elsewhere in the string. It looks up words, i.e. substrings made up of word characters, in the list.
gsubfn("\\w+", L, "Hello, name. You are age.")
## [1] "Hello, Eric. You are 42."
Upvotes: 6