mat mat - 2 months ago 10
R Question

R: sprintf to pad decimal number with leading white spaces

I'm trying to pad a decimal number with leading white spaces using the

sprintf
function.

For example, I would like to convert the following vector:

a <- c(1, 1.123, -1.123, 123)
[1] 1.000 1.123 -1.123 123.000


to (padding = 4):

[1] " 1.00" " 1.12" " -1.12" " 123.00"


I tried with
sprintf("% 4.2f", a)
but it produces the following result:

[1] " 1.00" " 1.12" "-1.12" " 123.00"


Edit:

I know that it works with integers, i.e.
sprintf("%4d", 123)
will produce
" 123"
, but I can't make it work with floating numbers.

Answer

Use %7.2f. 7 characters total, 2 to the right of the decimal.

sprintf("%7.2f", a)
# [1] "   1.00" "   1.12" "  -1.12" " 123.00"

Thanks for the hint from @Jota, we removed the space before 7.2f.

Comments