I would like to pass a constant to sprintf() function like:
This works:
sprintf("%.2f", pi)
[1] "3.14"
Now I would like to replace 2 by a constant x say 4:
x <- 4
sprintf("%.xf", pi)
Error in sprintf("%.xf", pi) :
invalid format '%.x'; use format %f, %e, %g or %a for numeric objects
Expected output:
[1] "3.1416"
>Solution :
You can use an asterisk * to set the precision via argument in the format string:
x <- 4
sprintf("%.*f", x, pi)
[1] "3.1416"