Home > Software engineering >  replace first occurence of character with X and second occurence of character with Y
replace first occurence of character with X and second occurence of character with Y

Time:10-07

I'm stuck with renaming a column in my data frame. I want to replace the first occurence of _ with an r and the second occurence of _ with a c.

dat <- data.frame(Q12_1_1 = NA)

While I can do two sequential str_replace (because it just replaces the first occurence), I'm wondering how a combined regex pattern could look like.

Works:

library(tidyverse)
dat |>
  rename_with(.cols = starts_with('Q12'),
              .fn = ~str_replace(., '_', 'r')) |>
  rename_with(.cols = starts_with('Q12'),
              .fn = ~str_replace(., '_', 'c'))

The question about n-th occurence of a pattern has been asked before (stringr remove n-th occurence of a character), but I'm not sure how I can specifically do different replacements for the same pattern.

Expected output:

data.frame(Q12r1c1 = NA)

CodePudding user response:

You could do:

dat <- data.frame(Q12_1_1 = NA)

library(tidyverse)

dat |>
  rename_with(.cols = starts_with('Q12'), .fn = ~ str_replace(., '_(\\d )_(\\d )', 'r\\1c\\2'))
#>   Q12r1c1
#> 1      NA

Or

dat |>
  rename_with(.cols = starts_with('Q12'), .fn = ~ str_replace(., '_(.*?)_', 'r\\1c'))
#>   Q12r1c1
#> 1      NA
  • Related