如何添加前導零?

我有一組看起來像這樣的數據: 服務器

anim <- c(25499,25500,25501,25502,25503,25504)
sex  <- c(1,2,2,1,2,1)
wt   <- c(0.8,1.2,1.0,2.0,1.8,1.4)
data <- data.frame(anim,sex,wt)

data
   anim sex  wt anim2
1 25499   1 0.8     2
2 25500   2 1.2     2
3 25501   2 1.0     2
4 25502   1 2.0     2
5 25503   2 1.8     2
6 25504   1 1.4     2

我但願在每一個動物ID以前添加一個零: app

data
   anim sex  wt anim2
1 025499   1 0.8     2
2 025500   2 1.2     2
3 025501   2 1.0     2
4 025502   1 2.0     2
5 025503   2 1.8     2
6 025504   1 1.4     2

出於興趣考慮,若是我須要在動物ID以前添加兩個或三個零該怎麼辦? ide


#1樓

擴展@goodside的響應: 函數

在某些狀況下,您可能但願用零填充字符串(例如,fip代碼或其餘相似數字的因子)。 在OSX / Linux中: ui

> sprintf("%05s", "104")
[1] "00104"

可是因爲sprintf()調用了操做系統的C sprintf()命令(在此進行了討論),所以在Windows 7中,您會獲得不一樣的結果: spa

> sprintf("%05s", "104")
[1] "  104"

所以,在Windows計算機上,解決方法是: 操作系統

> sprintf("%05d", as.numeric("104"))
[1] "00104"

#2樓

str_pad包中的stringr是替代方法。 code

anim = 25499:25504
str_pad(anim, width=6, pad="0")

#3樓

data$anim <- sapply(0, paste0,data$anim)

#4樓

這是在字符串(例如CUSIP)中添加前導0的另外一種選擇,有時看起來像數字,而且許多應用程序(例如Excel)會破壞並刪除前導0或將其轉換爲科學計數法。 ip

當我嘗試@metasequoia提供的答案時,返回的向量有前導空格而不是0 s。 這是@ user1816679提到的相同問題-刪除0先後的引號或從%d更改成%s也沒有任何區別。 僅供參考,我正在使用在Ubuntu服務器上運行的RStudio服務器。 這個小小的兩步解決方案爲我工做: 字符串

gsub(pattern = " ", replacement = "0", x = sprintf(fmt = "%09s", ids[,CUSIP]))

使用magrittr軟件包中的%>%管道函數,它看起來可能像這樣:

sprintf(fmt = "%09s", ids[,CUSIP]) %>% gsub(pattern = " ", replacement = "0", x = .)

我更喜歡一種功能的解決方案,可是它能夠工做。


#5樓

對於但願數字字符串保持一致的其餘狀況,我作了一個函數。

有人可能會發現這頗有用:

idnamer<-function(x,y){#Alphabetical designation and number of integers required
    id<-c(1:y)
    for (i in 1:length(id)){
         if(nchar(id[i])<2){
            id[i]<-paste("0",id[i],sep="")
         }
    }
    id<-paste(x,id,sep="")
    return(id)
}
idnamer("EF",28)

抱歉,格式化。

相關文章
相關標籤/搜索