简体   繁体   中英

Add leading zeros only if the number starts with 6 in R dataframe

I have a dataframe with numbers that I need to format. How do I add leading zeroes to only numbers that starts with 6? All examples seen using str_pad() or sprintf() are not exactly like my task, and I found it challenging to adapt them. My dummy dataframe is below:

dummy_numbers
621103 
06102658  
19562106    
61102
0635467

The desired result is:

desired_numbers
0621103 
06102658  
19562106    
061102
0635467

Thanks.

You may add 0 to only those numbers that start with 6. This can be written as -

transform(df, dummy_numbers = 
              paste0(ifelse(grepl('^6', dummy_numbers), "0", ""), dummy_numbers))

#  dummy_numbers
#1       0621103
#2      06102658
#3      19562106
#4        061102
#5       0635467

Without ifelse -

inds <- grepl('^6', df$dummy_numbers)
df$dummy_numbers[inds] <- paste0(0, df$dummy_numbers[inds])
df

Your can use grepl() and regex ( ^ ) to capture the start of a string.

library(tidyverse)

df %>% mutate(dummy_numbers = ifelse(grepl("^6", dummy_numbers), 
                                     paste0(0, dummy_numbers), 
                                     dummy_numbers))

We just need a simple "leading-6" regex:

gsub("^6", "06", dummy)
# [1] "0621103"  "06102658" "19562106" "061102"   "0635467" 

identical(gsub("^6", "06", dummy), desired)
# [1] TRUE

Data

dummy <- c("621103", "06102658", "19562106", "61102", "0635467")
desired <- c("0621103", "06102658", "19562106", "061102", "0635467")

Another option is to use str_replace to capture numbers starting with 6 then replace with 06 :

library(tidyverse)

df %>% 
  mutate(dummy_numbers = str_replace(dummy_numbers, "^6", "06"))

Output

  dummy_numbers
1       0621103
2      06102658
3      19562106
4        061102
5       0635467

Data

df <-
  structure(list(dummy_numbers = c(
    "621103", "06102658", "19562106", 
    "61102", "0635467"
  )),
  class = "data.frame",
  row.names = c(NA,-5L))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM