Is it somehow possible to feed R's sprintf(fmt, ...) function with a list or data.frame instead of seperate vectors?
for example, what I want to achieve:
df <- data.frame(v1 = c('aa','bb','c'),
v2 = c('A', 'BB','C'),
v3 = 8:10,
stringsAsFactors = FALSE)
sprintf('x%02s%02s%02i', df[[1]], df[[2]], df[[3]])
[1] "xaa A08" "xbbBB09" "x c C10"
but with a more concise Syntax like:
sprintf('x%02s%02s%02i', df)
Error in sprintf("x%02s%02s%02i", df) : too few arguments
In my real situation I have many more columns to feed sprintf, making the code ugly.
I guess more generally the question is how to circumvent the ellipsis ...
function.
I'm sure not the first one to ask that but I couldn't find anything in this direction..
You can make it a function and use do.call
to apply, i.e.,
f1 <- function(...){sprintf('x%02s%02s%02i', ...)}
do.call(f1, df)
#[1] "xaa A08" "xbbBB09" "x c C10"
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