简体   繁体   中英

how to print a variable number of arguments in r?

new to r. this question has answers here and here .

But these do not seem answer the question in the case of:

vec <- c("a","b","c","d")
s<-do.call(sprintf, c(list("%s %s"), vec))

The doc says: " ... The arguments (including fmt) are recycled if possible a whole number of times to the length of the longest, and then the formatting is done in parallel. ... "

The code below shows that this is not happening:

> vec <- c("a","b","c","d")
> s<-do.call(sprintf, c(list("%s %s"), vec))
> print(s)
[1] "a b"
> v1 <- c("foo", "bar", "baz","foo", "bar", "baz")
> base_string = "%s, %s, %s"
> s<-do.call(sprintf, c(fmt = base_string, as.list(v1)))
> print(s)
[1] "foo, bar, baz"
> 

How do i make this print out all of the values?

Edit: according to @mt1022, i misread the doc. he suggests: sprintf(paste0(v1, collapse = ' ')) which works.

Thanks to @chinsoon12 for the hint.

What I really want to do is something like this:

> s<-NA
> v<-c(1,"2",pi,2,"foo",2*pi)
> s<-do.call(sprintf, c(v, list(fmt=paste(rep("%d %s %f", length(v)/3), collapse=" "))))
Error in (function (fmt, ...)  : 
  invalid format '%d'; use format %s for character objects
> print(s)
[1] NA
>

The answer (thanks to @mt1022) is to use a list instead of a vector:

v<-list(1,"2",pi,2,"foo",2*pi)
s<-do.call(sprintf, c(v, list(fmt=paste(rep("%d %s %f", length(v)/3), collapse=" "))))

The doc is right. In first case, do.call(sprintf, c(list("%s %s"), vec)) is equal to:

sprintf("%s %s", "a","b","c","d")

The fmt string "%s %s" requires two vectors while you provided four and the last two ("c", "d") were not used for printing.

The second case is similar. do.call(sprintf, c(fmt = base_string, as.list(v1))) is equal to:

sprintf(fmt = "%s, %s, %s", "foo", "bar", "baz","foo", "bar", "baz")

Three variables were to be printed based on fmt but you provided six.


Then, what does "recycled" in the doc mean?

and I guess you might misunderstand it. It means when the formating string and vectors are of different lengths, the short er ones will be recycled to the longest one. An example:

> sprintf(c('%s %s', '%s, %s'), c('a', 'b', 'c'), 1:6)
[1] "a 1"  "b, 2" "c 3"  "a, 4" "b 5"  "c, 6"

How to print variable number of arguments : You can try paste :

> sprintf(paste0(vec, collapse = ' '))
[1] "a b c d"
> sprintf(paste0(v1, collapse = ', '))
[1] "foo, bar, baz, foo, bar, baz"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM