Search code examples
rconcatenationnumber-formattingoutput-formatting

Concatenate numbers into string output, formatting each number to take same character width


I have a vector

a<-c(18.123412, 0, 1.5, 34.123, 2.1)

And I want to create a string from it.

paste(round(a,3), collapse = " " )

Everything is working nice, but the problem that I want the output for an each number to be the same, by this I mean the following. Now I have

"18.123 0 1.5 34.123 2.1"

and I need

"18.123 0___ 1.5__ 34.123 2.1__"

Here _ denote the idea that because the number has smaller amount of digits, we need to substitute them with space. Any idea how I can achieve this?


Solution

  • Use formatC:

    formatC(a, width=10, drop0trailing=TRUE)
    [1] "     18.12" "         0" "       1.5" "     34.12" "       2.1"
    

    To paste into a single string, use the argument collapse="":

    paste0(formatC(a, width=10, drop0trailing=TRUE), collapse="")
    [1] "     18.12         0       1.5     34.12       2.1"
    

    To left justify, use the argument flag="-":

    formatC(a, width=10, drop0trailing=TRUE, flag="-")
    [1] "18.12     " "0         " "1.5       " "34.12     " "2.1       "
    

    See ?formatC, ?prettyNum or ?format for more help and other options.