Reputation: 4889
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
Reputation: 79298
sub("(.*?)(wrong|punish)","\\1_\\2",names(x))
[1] "neu_wrong" "acc_wrong" "att_punish" "int_punish"
Upvotes: 1
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