list input to sprintf (circumvent the ellipsis ... function)
Asked Answered
T

2

6

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..

Teufert answered 21/5, 2017 at 18:36 Comment(0)
C
10

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"
Chesna answered 21/5, 2017 at 18:46 Comment(0)
R
2

We can also use without anonymous function call

do.call(sprintf, c(df, fmt = 'x%02s%02s%02d'))
#[1] "xaa A08" "xbbBB09" "x c C10"

Or another option is

library(stringr)
paste0('x', do.call(paste0, Map(str_pad, df, width = 2, pad = c(' ', ' ', '0'))))
#[1] "xaa A08" "xbbBB09" "x c C10"
Reticulation answered 21/5, 2017 at 18:50 Comment(2)
imo this is basically the same as @Sotos' answerFrodin
Very helpful to point out how to combine multiple args to the function by c() in do.call. See example in do.call documentation. Concise. Will use that. ThanksTeufert

© 2022 - 2024 — McMap. All rights reserved.