loop with paste0 problem

hello it's me again, I have a series of strings of various length and I want all of them to be of length 3. So I wrote this quite simple but (supposedly) effective code and for some reason the paste0 method apply on strings that doesn't meet the condition I set in my loop plus you can see the result of str_length for different strings :

data<-c("4" ,  "14"  ,"33" , "34" , "43" , "53",  "93"  ,"142", "143" ,"160", "173", "185", "194", "202","244", "249")

library(tidyverse)

str_length(data[1])
#> [1] 1
str_length(data[5])
#> [1] 2
str_length(data[10])
#> [1] 3

for (i in 1:length(data)) {
  if (str_length(data[i])==1) {
    data[i]<-paste0("00",data[i])
    
  }
  if (str_length(data[i]==2)) {
    data[i]<-paste0("0",data[i])
  }
}

data
#>  [1] "0004" "014"  "033"  "034"  "043"  "053"  "093"  "0142" "0143" "0160"
#> [11] "0173" "0185" "0194" "0202" "0244" "0249"

Just use this:

str_pad(data, 3, "left", "0")

This is an excellent example of the power of functional programming - Nice! :+1:

Genious I didn't know about that function Thank you !!

yes it is but I still don't understand why my loop doesn't get the job done :frowning:

brackets are messed up

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.