Search code examples
rstring-length

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"


I have this data frame:

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

If their the name of characters of each row is 5 I need to add a "0" at the beginning of the string. I am trying these code, but it is adding a "0" to every row:

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

Solution

  • Several possible approaches to solve this problem have been described in the comments. Here's another one. It uses the stri_pad_left() function from the stringi package.

    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"