在 R 中的字符串开头添加一个带有条件的“0”,它与 "Add zeros to R because it has a condition" 不同

add a "0" with a condition to the beginning of a string in R it is different to "Add zeros to R because it has a condition"

我有这个数据框:

bloqueados$HoraLlamada<- as.character(c(83048, 163112, 115929, 123632, 114541,  72807 163626, 130051,  81645, 121639))

如果他们每行的字符名称是5,我需要在字符串的开头添加一个“0”。我正在尝试这些代码,但它向每一行添加了一个“0”:

for (i in bloqueados$HoraLlamada){
    if(nchar(bloqueados$HoraLlamada)==5){
        bloqueados$HoraLlamada2<- paste("0",bloqueados$HoraLlamada)
    }else{
        bloqueados$HoraLlamada2<-paste(bloqueados$HoraLlamada)
    }
}

评论中描述了解决此问题的几种可能方法。这是另一个。它使用 stringi 包中的 stri_pad_left() 函数。

nums <-  as.character(c(83048, 163112, 115929, 123632, 114541,  72807, 163626, 130051,  81645, 121639))
library(stringi)
stri_pad_left(nums, pad="0", width = 6)
#[1] "083048" "163112" "115929" "123632" "114541" "072807" "163626" "130051" "081645" "121639"