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

时间:2018-02-09 01:17:07

标签: r regex stringr

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

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

2 个答案:

答案 0 :(得分:2)

不需要使用stringr。您可以使用

在基本R中执行此操作
sub("(wrong|punish)", "_\\1", names(x))
[1] "neu_wrong"  "acc_wrong"  "att_punish" "int_punish"

答案 1 :(得分:1)

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