这与我的问题密切相关: 数据框中的str_replace?
所以我想解决这个问题:
dog_descriptions <- data.frame(breed_primary = c("Pit Bull Terrier",
"Labrador Retriever",
"Border Collie"),
number_of_legs = rep(4, 3))
dog_descriptions2 <-
dog_descriptions %>%
mutate(breed_primary2 = str_replace_all(breed_primary, c("Pit Bull Terrier" = "Pit Bull\nTerrier", "Labrador Retriever" = "Labrador\nRetriever", "Border Collie" = "Border\nCollie")))
但不使用长文本字符串,而是使用 data.frame replacement_input:
R 中是否有可能使用对象(例如名为 replacement_input 的数据框)来替换复杂的文本字符串。
replacement_input <- data.frame(replace = c("Pit Bull Terrier",
"Labrador Retriever",
"Border Collie"),
replace_with = c("Pit Bull\nTerrier",
"Labrador\nRetriever",
"Border\nCollie" ))
转换为这种格式应该会有所帮助:
c("Pit Bull Terrier" = "Pit Bull\nTerrier", "Labrador Retriever" = "Labrador\nRetriever", "Border Collie" = "Border\nCollie"))
我没有成功地结合paste0和stringr::str_c来创建“替换向量”
也许这也是错误的做法。
来自文档:
替换值通常是单个字符串,但它可以是与字符串或模式长度相同的向量。 换句话说,将模式作为一个向量传递,将替换作为另一个向量传递,这一切都有效。
实践中:
dog_descriptions %>%
mutate(breed_primary2 = str_replace_all(breed_primary, replacement_input$replace, replacement_input$replace_with))
更新:工作代码/可重现的示例:
replacement_input <- data.frame(replace = c("Pit Bull Terrier",
"Labrador Retriever",
"Border Collie"),
replace_with = c("Pit Bull\nTerrier",
"Labrador\nRetriever",
"Border\nCollie" ))
data.frame(breed_primary = c("Pit Bull Terrier",
"Labrador Retriever",
"Border Collie"),
number_of_legs = rep(4, 3)) %>%
mutate(breed_primary2 = str_replace_all(breed_primary, replacement_input$replace, replacement_input$replace_with))