0

Let's say I have this data frame:

df <- as.data.frame(c("77111","77039","5005","4032"))

and I want to create a new column where if the values start with "77", then remove the "77" and extract the remaining numbers. Otherwise, keep the values as is so that the new column looks like this:

df <- df %>% mutate(new_numbers =c("111","039","5005","4032"))
zx8754
  • 52,746
  • 12
  • 114
  • 209
karuno
  • 391
  • 4
  • 12

3 Answers3

2

We can use str_remove to remove the 77 from the start (^) of the column

library(dplyr)
library(stringr)
df <- df %>% 
           mutate(col = str_remove(col, "^77"))

data

df <- data.frame(col= c("77111","77039","5005","4032"))
akrun
  • 874,273
  • 37
  • 540
  • 662
1

Another...

df <- df %>%
   mutate(new_numbers =  gsub('^77', '', original_column))
TTS
  • 1,818
  • 7
  • 16
0

For an approach in base R, just use gsub:

df$new <- gsub(pattern = "^77",
               replacement = "", 
               string = df[,1])
Zoey RW
  • 185
  • 1
  • 15