I know paste()
and paste0()
are extremely popular in R, but I find myself often using sprintf()
when I want to build a long string with some variables.
For example
x <- "a"
y <- 10
paste0("The value of x is ", x, " and y is ", y, ".")
sprintf("The value of x is %s and y is %d.", x, y)
I find the sprintf()
version much easier to write and the code less clunky. I couldn't find any discussion of the benefits of one over the other. Is there any reason for me not to use sprintf()
when the basic functionality of paste
is all I need? (if I need to use the collapse
or sep
arguments then obviously sprintf()
will not do).
The only thing I can think of is that maybe sprintf()
is slower because it checks that the types match.
One reason I could think of to use paste0
or paste
instead of sprintf
is that you don't need to think about the types of arguments being passed.
In terms of efficiency, sprintf
appears to have an edge, at least on the example you gave and my machine:
library(microbenchmark)
microbenchmark(paste0("The value of x is ", x, " and y is ", y, "."),
sprintf("The value of x is %s and y is %d.", x, y))
# Unit: microseconds
# expr min lq mean median uq max neval
# paste0("The value of x is ", x, " and y is ", y, ".") 2.924 3.0185 3.45632 3.0950 3.1575 36.421 100
# sprintf("The value of x is %s and y is %d.", x, y) 1.328 1.4130 1.54794 1.4535 1.5430 7.513 100
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With