I wish to insert a defined variable into a string in R, where the variable will be inserted in multiple places.
I have seen the sprintf
may be of use.
Example of desired input:
a <- "tree"
b <- sprintf("The %s is large but %s is small. %s", a)
Ideal output would return
"The tree is large but tree is small. tree"
I understand that I can use the function like this:
b <- sprintf("The %s is large but %s is small. %s",a,a,a)
However for my actual work I would require the insert 10+ times, so i'm looking for a cleaner/simpler solution.
Would gsub be a better solution?
My exact question has been answered here however it is for the language Go:
Replace all variables in Sprintf with same variable
Here is an actual sprintf() solution:
a <- "tree"
sprintf("The %1$s is large but %1$s is small. %1$s", a)
[1] "The tree is large but tree is small. tree"
There are more examples in the official sprintf() documentation.
1) do.call Using do.call
the a
arguments could be constructed using rep
. No packages are used.
a <- "tree"
s <- "The %s is large but %s is small. %s"
k <- length(gregexpr("%s", s)[[1]])
do.call("sprintf", as.list(c(s, rep(a, k))))
## [1] "The tree is large but tree is small. tree"
2) gsub This has already been mentioned in the comments but gsub
could be used. Again, no packages are used.
gsub("%s", a, s, fixed = TRUE)
## [1] "The tree is large but tree is small. tree"
3) gsubfn The gsubfn package supports a quasi-perl style string interpolation:
library(gsubfn)
a <- "tree"
s2 <- "The $a is large but $a is small. $a"
fn$c(s2)
## [1] "The tree is large but tree is small. tree"
Also, backticks can be used to enclose entire R expressions which are evaluated and substituted in.
This can be used with any function, not just c
leading to very compact code. For example suppose that we want to count the characters in s
after substitution. Then it could be done like this:
fn$nchar(s2)
## [1] 38
4) $n format notation In sprintf
the notation %n$
refers to the nth argument following fmt
:
a <- "tree"
s <- "The %1$s is large but %1$s is small. %1$s"
sprintf(s, a)
## [1] "The tree is large but tree is small. tree"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With