2017-08-09 60 views
0

我需要格式化數字,右對齊逗號符號的左右固定寬度,而不考慮數字。例如逗號左邊的3位數字和右邊的兩位數字。因此12.3將被格式化爲" 12.30"。我想出了最好的解決辦法是這樣的:格式化數字右對齊R,長於最長數字

test <- c(10, 1, 0.1, 0.01, 0.001, 0) 

format(round(c(100,test), 2), 
    justify = "right", 
    scientific = FALSE, 
    nsmall = 2)[-1] 

有直接formatprintfsprintf歸檔本的方式,...

回答

1
test <- c(10, 1, 0.1, 0.01, 0.001, 0) 
formatC(test, width = 6, digits = 2, format = "f") 
#[1] " 10.00" " 1.00" " 0.10" " 0.01" " 0.00" " 0.00" 

顯然,這是一個軟寬度規格。如果您對左邊超過三位數,寬度增加,以適應:

formatC(100000, width = 6, digits = 2, format = "f") 
#[1] "100000.00" 
+0

非常感謝,我試過的許多參數組合'format','formatC','printf','的sprintf '沒有找到這個。 – snaut

+0

我通過仔細閱讀'help(「formatC」)''中的文檔瞭解了這一點。我承認,'formatC'接受了不少參數,但在翻頁網站上它非常靈活。你也可以用'sprintf'來做到這一點。 – Roland