Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple variables in Sprintf with same value

Tags:

string

format

r

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

like image 216
tfcoe Avatar asked Mar 05 '18 12:03

tfcoe


2 Answers

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.

like image 168
sindri_baldur Avatar answered Sep 20 '22 23:09

sindri_baldur


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"
like image 40
G. Grothendieck Avatar answered Sep 18 '22 23:09

G. Grothendieck