Home > Net >  Is it possible to repeat a variable in sprintf() in R?
Is it possible to repeat a variable in sprintf() in R?

Time:11-30

I created a function that takes 2 variables and one string as input.
f <- function(a,b, string) { ... sprintf(string, a, b) }

Imagine that the string is "1:%s ; 2:%s" then the output will be "1:a : 2:b" with a and b being inputs of the function f.
I want to include as input also strings with more than 2 '%s' such as
"1:%s ; 2:%s ; 3:%s ; 4:%s"
and the output should be
"1:a ; 2:b ; 3:a ; 4:b"
Basically I want to use sprintf() only with 2 inputs that repeat many times based on how many spots need to be filled out.

I know that i can just change the code and add more parameters for the second case such as
sprintf(string, a,b,a,b), but for some reasons i do not want to do that. I just need a way to repeat the parameters inside the sprintf function.

CodePudding user response:

sprintf doesn't recycle these values. However, you can reference the value by position:

sprintf("1:%1$s ; 2:%2$s ; 3:%1$s ; 4:%2$s", "a", "b")
#[1] "1:a ; 2:b ; 3:a ; 4:b"

It's unclear why you can't repeat the values. Why can't you program the recycling if you need it?

foo <- function(fmt, ...) {
  m <- length(gregexpr("%s", fmt, fixed = TRUE)[[1]])
  args <- list(...)
  n <- ceiling(m/length(args))
  args <- rep(args, n)
  args <- args[seq_len(m)]
  do.call(sprintf, c(args, fmt = fmt))
}

foo("1:%s ; 2:%s ; 3:%s ; 4:%s", "a", "b")
#[1] "1:a ; 2:b ; 3:a ; 4:b"
  • Related