2011-11-25 87 views
105

以下代碼格式編號爲固定寬度,帶前導零

a <- seq(1,101,25) 
b <- paste("name", 1:length(a), sep = "_") 

產生這樣的輸出:

"name_1" "name_26" "name_51" "name_76" "name_101" 

我想有所有值的相同寬度,這意味着爲我用這樣的零填充值:

"name_001" "name_026" "name_051" "name_076" "name_101" 

我該如何處理?

(此問題被有關this one

回答

176

有幾種解決方案這一點。其中之一是使用sprintf。這使用嵌入在字符串中的C樣式格式代碼來指示傳遞給它的任何其他參數的格式。例如,格式代碼%3d裝置的格式將數字作爲寬度3的整數:

a <- seq(1,101,25) 
sprintf("name_%03d", a) 
[1] "name_001" "name_026" "name_051" "name_076" "name_101" 

另一個是formatCpaste

paste("name", formatC(a, width=3, flag="0"), sep="_") 
[1] "name_001" "name_026" "name_051" "name_076" "name_101"