查找字符串中第一次出现的单词并在单词前添加下划线

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

我想在某个单词的第一次出现处插入下划线。我怎样才能做到这一点?下面是我试过的代码-

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

不需要stringr。您可以使用

在 base R 中执行此操作
sub("(wrong|punish)", "_\1", names(x))
[1] "neu_wrong"  "acc_wrong"  "att_punish" "int_punish"
sub("(.*?)(wrong|punish)","\1_\2",names(x))
[1] "neu_wrong"  "acc_wrong"  "att_punish" "int_punish"