String extract and replace to get a specific result

Hi Sir/Madam
Need an urgent string wrangling to load the data for further analysis.
Basically, prefix 00 to be replaced with 'ED' and keep the numbers after prefix 00.
Result column is the desired outcome.
Thank you very much.
repex is pasted here.

ed.sample <- tibble::tribble(
                       ~id,     ~result,
               "001565100", "ED1565100",
               "001565104", "ED1565104"
               )
ed.sample
#> # A tibble: 2 x 2
#>   id        result   
#>   <chr>     <chr>    
#> 1 001565100 ED1565100
#> 2 001565104 ED1565104

Created on 2024-10-04 with reprex v2.1.1

1 Like
library(tidyverse)

(ed.sample <- tribble(
  ~id, ~result,
  "001565100", "ED1565100",
  "001565104", "ED1565104"
))

(in_1 <- select(ed.sample, id))

(ed.result <- mutate(in_1,
  result = paste0("ED", str_sub(id, 3, nchar(id)))
))

identical(
  ed.sample,
  ed.result
)
1 Like

@nirgrahamuk thank you very much for your prompt response. You saved my life. Appreciated.

Since you are loading the tidyverse library (which includes the stringr library) this can be accomplished more simply by:

ed.sample %>% 
    mutate(result = str_replace(id, "^00", "ED"))
1 Like

@kilonovember Thank you very much.

The base R solution would be:

ed$result <- sub("^00", "ED", ed$id)

Which will return exactly the same as @kilonovember's suggestion.

1 Like

@Scoco Thank you very much for your simple base R one. G

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.