Entering edit mode
2.8 years ago
Phylicia
▴
10
Hello! I have already written a code for this question, but my code is very complex. I want to enquiry, is there any simpler way to achieve the same goal. Thanks a lot!
Background: There is a column named id, in which there are 5 digit numbers and 6 digit numbers.
Aim: I want to select 5 digit numbers and add a zero in front of them and merge added-0 items with the original 6 digit numbers.
df is the name of the data frame.
#Select the columns whose ID digit is only 5 and add 0 in front of it.
df1 <- subset(df, nchar(as.character(df$id)) == 5)
df1 <- df1 %>% mutate("NewID"= paste0("0", df1$id))
#Select the columns whose ID digit is only 6 and merge it with the first subset
df2 <- subset(df, nchar(as.character(df$id)) == 6)
df2 <- df2 %>% mutate("NewID"= df2$id)
#Merge them
df3 <- rbind(df1, df2)
a typo or copy/paste issue in this line
df <- mutate(df, id=str_pad(id, 6, "left"))
. In addition, for long numbers, user must setscipen
so that number is not turned toe
notation, withstr_pad
.str_pad
has some weird behavior (from user point of view, ifscipen
is not set)Forgot to add 0 padding to it, thanks for pointing it out!
Thanks a lot for your kind help!