Indrajeet Patil
Indrajeet Patil

Reputation: 4889

finding first occurrence of a word in a string and adding underscore before the word

I want to insert an underscore at the first occurrence of a certain word. How can I do this? Below is the code I have tried-

library(stringr)

# dataframe
x <-
  tibble::as.tibble(cbind(
    neuwrong = c(1:4),
    accwrong = c(1:4),
    attpunish = c(1:4),
    intpunish = c(1:4)
  ))

# display the dataframe
x
#> # A tibble: 4 x 4
#>   neuwrong accwrong attpunish intpunish
#>      <int>    <int>     <int>     <int>
#> 1        1        1         1         1
#> 2        2        2         2         2
#> 3        3        3         3         3
#> 4        4        4         4         4

# attempt to split the string and adding underscore
names(x) <- str_replace(string = names(x), 
            pattern = "(.*)^(.*)wrong$|(.*)^(.*)punish$",
            replacement = "\\1_\\2")

# display dataframe with the new names
x
#> # A tibble: 4 x 4
#>    `NA`  `NA`  `NA`  `NA`
#>   <int> <int> <int> <int>
#> 1     1     1     1     1
#> 2     2     2     2     2
#> 3     3     3     3     3
#> 4     4     4     4     4

# needed output
#> # A tibble: 4 x 4
#>   neu_wrong acc_wrong att_punish int_punish
#>       <int>     <int>      <int>      <int>
#> 1         1         1          1          1
#> 2         2         2          2          2
#> 3         3         3          3          3
#> 4         4         4          4          4

Upvotes: 2

Views: 50

Answers (2)

Onyambu
Onyambu

Reputation: 79298

sub("(.*?)(wrong|punish)","\\1_\\2",names(x))
[1] "neu_wrong"  "acc_wrong"  "att_punish" "int_punish"

Upvotes: 1

G5W
G5W

Reputation: 37661

No need for stringr. You can do this in base R with

sub("(wrong|punish)", "_\\1", names(x))
[1] "neu_wrong"  "acc_wrong"  "att_punish" "int_punish"

Upvotes: 2

Related Questions