Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list input to sprintf (circumvent the ellipsis ... function)

Tags:

r

printf

ellipsis

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

like image 664
rluech Avatar asked May 21 '17 18:05

rluech


1 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" "x c C10"
like image 198
Sotos Avatar answered Sep 21 '22 08:09

Sotos