'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.
Solution 1:[1]
dplyr
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))
Or simply use a gsub()
or sub()
df %>% mutate(dummy_numbers = gsub("^6", "06", dummy_numbers))
base R
df[, "dummy_numbers"] <- gsub("^6", "06", df[["dummy_numbers"]])
Solution 2:[2]
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")
Solution 3:[3]
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
Solution 4:[4]
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))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | r2evans |
Solution 3 | Ronak Shah |
Solution 4 |