Search code examples
rdatatablealignmentright-align

I cannot right-align the data in a column in a table


I cannot right-align the data in a column in a table (in the fifth column). When I print as txt, the figures in the column are not aligned because of the minus signs. (in the fifth column)

WINGEN01    20001   1.02000   0.09000   -1.37000   0.25000   0.19000   0.09000
WINGEN01    20002   1.07000   0.10000   -2.02000   0.25000   0.25000   0.09000
WINGEN01    20003   0.53000   0.09000   0.33000   0.45000   0.23000   0.09000
WINGEN01    20004   1.32000   0.19000   1.23000   0.09000   0.23000   0.03000
WINGEN01    20005   1.16000   0.16000   0.62000   0.14000   0.26000   0.04000
WINGEN01    20006   1.28000   0.15000   0.51000   0.11000   0.20000   0.04000
WINGEN01    20007   0.98000   0.13000   0.64000   0.15000   0.14000   0.05000
WINGEN01    20008   1.17000   0.15000   0.88000   0.10000   0.20000   0.03000
WINGEN01    20009   0.42000   0.06000   -1.43000   0.60000   0.19000   0.10000
WINGEN01    20010   1.06000   0.40000   3.18000   0.52000   0.22000   0.02000
WINGEN01    20011   1.28000   0.15000   0.76000   0.10000   0.21000   0.03000
WINGEN01    20012   0.47000   0.06000   -1.30000   0.57000   0.22000   0.10000
WINGEN01    20013   1.14000   0.14000   0.97000   0.10000   0.16000   0.03000




write.table(Y_14_PAR, paste("Y_14_PAR.PAR"),  quote = F, row.names = F, col.names =F,sep = "   ")

Solution

  • sprintf may be the command you need. It is a C-style string formatting command that belongs to base R. Example below.

    data.frame(a = sprintf("%-1.5f", pi*-3:3))
    
    # output NOT RUN
    
             a
    1 -9.42478
    2 -6.28319
    3 -3.14159
    4  0.00000
    5  3.14159
    6  6.28319
    7  9.42478
    
    # NOT RUN
    

    Note that it is the minus sign after the % that left justifies the numbers. There's no right justify that I can tell but I think it will do the job. Otherwise, replace with + in order to force the sign for both +/-.

    Also make sure that you wrap the function in an as.numeric() so you don't accidentally coerce the data type.