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=" "))))