问题
I have mostly used paste
or paste0
for my pasting tasks in the past, but I'm pretty fascinated by the speed of sprintf
. Yet I feel that I'm lacking some its basics.
Just wondered if there's also a way to collapse a multi-element character vector to one of length 1 as paste
would do when using its collapse
argument, that is, without having to specify respective wildcards and its values manually (in paste
, I simply leave the task up to the function to find out how many elements should be collapsed).
x <- c("Pasted string:", "hello", "world!")
> sprintf("%s %s %s", x[1], x[2], x[3])
[1] "Pasted string: hello world!"
> paste(x, collapse=" ")
[1] "Pasted string: hello world!"
I'm looking for something like this (pseudo code)
> sprintf("<the-correct-parameter>", x)
[1] "Pasted string: hello world"
For the interested: benchmark of sprintf
vs. paste
require("microbenchmark")
t1 <- median(microbenchmark(sprintf("%s %s %s", x[1], x[2], x[3]))$time)
t2 <- median(microbenchmark(paste(x, collapse=" "))$time)
> t1/t2
[1] 0.7273114
回答1:
The function sprintf recycles its format string, so for example the code
cat(sprintf("%8.4f",rnorm(5)),"\n")
prints something like
-0.5685 -0.6481 0.6296 -0.0043 -1.4763
str = sprintf("%8.4f",rnorm(5))
stores the output in a vector of strings and
str_one = paste(sprintf("%8.4f",rnorm(5)),collapse='')
stores the output in a single string. The format string does not need to specify the number of floats to be printed. This also holds for printing integers and strings with the %d and %s formats.
来源:https://stackoverflow.com/questions/23654521/collapsing-character-vectors-with-sprintf-instead-of-paste