我正在尝试查找并替换由字符串组成的数据框架的某些值。像以下工作一样的简单情况,
library(stringr)
test1 <- c("one", "two", "three")
str_replace_all(string = test1,
pattern = c('one' = "1ne",
'three' = "3ree"))
> [1] "1ne" "two" "3ree"
但是,一个更复杂的案例(如以下情况(不起作用。我在这里做错了什么?
test2 <- c("one (1) x1", "two (2) x2", "three (3) x3")
test2 <- c("one (1) x1", "two (2) x2", "three (3) x3")
str_replace_all(string = test2,
pattern = c('one (1) x1' = "X1",
'two (2) x2' = "X2"))
> [1] "one (1) x1" "two (2) x2" "three (3) x3"
使用修复以避免正则匹配
str_replace_all(string = test2,
pattern = fixed(c('one (1) x1' = "X1",
'two (2) x2' = "X2")))
# [1] "X1" "X2" "three (3) x3"