Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically insert string width value into sprintf()

Tags:

string

r

printf

I am trying to programmatically insert the string width value into a sprintf() format.

The desired result is

sprintf("%-20s", "hello")
# [1] "hello               "

But I want to insert the 20 on the fly, in the same call, so that it can be any number. I have tried

sprintf("%%-%ds", 20, "hello")
# [1] "%-20s"
sprintf("%-%ds", 20, "hello")
# Error in sprintf("%-%ds", 20, "hello") : 
#   invalid format '%-%d'; use format %f, %e, %g or %a for numeric objects
sprintf("%-%%ds", 20, "hello")
# Error in sprintf("%-%%ds", 20, "hello") : 
#   invalid format '%-%%d'; use format %f, %e, %g or %a for numeric objects

Is this possible in sprintf()?

like image 584
Rich Scriven Avatar asked Dec 24 '22 01:12

Rich Scriven


1 Answers

Yes, This is possible by using the asterisk *.

As mentioned in the docs,

A field width or precision (but not both) may be indicated by an asterisk *: in this case an argument specifies the desired number

Hence the code would be

> sprintf("%-*s", 20, "hello")
[1] "hello               "
like image 187
Bhargav Rao Avatar answered Dec 28 '22 08:12

Bhargav Rao