Input list for sprintf (bypassing the ellipse function ...)

Is it possible to somehow combine the function R sprintf (fmt, ...) with a list or data.frame instead of individual 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" "xc C10" 

but with more concise syntax, for example:

 sprintf('x%02s%02s%02i', df) Error in sprintf("x%02s%02s%02i", df) : too few arguments 

In my real situation, I still have many columns to feed sprintf, which makes the code ugly.

I think that in general, the question is how to get around the ellipsis function ...

I am sure that this is not the first to ask about this, but I could not find anything in this direction.

+5
source share
2 answers

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" "xc C10" 
+9
source

We can also use functions without anonymous calling

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

Or another option

 library(stringr) paste0('x', do.call(paste0, Map(str_pad, df, width = 2, pad = c(' ', ' ', '0')))) #[1] "xaa A08" "xbbBB09" "xc C10" 
+2
source

Source: https://habr.com/ru/post/1268072/


All Articles