我有一个这样的数据框:
df <- data.frame(id = c(1,2), keywords = c("google, yahoo, air, cookie", "cookie, air"))
我想实现如下规则:
stocks <- c("google, yahoo")
climate <- c("air")
cuisine <- c("cookie")
然后得到这样的结果:
df_ne <- data.frame(id = c(1,2), keywords = c("stocks, climate, cuisine", "climate, cuisine")
这怎么可能?
最佳答案
您可以使用 stringr
包中的 str_replace_all
library(dplyr)
library(stringr)
df <- data.frame(id = c(1,2), keywords = c("google, yahoo, air, cookie", "cookie, air"))
df %>%
mutate(keywords = str_replace_all(keywords,
c("google, yahoo" = "stocks","air" = "climate", "cookie" = "cuisine")))
关于换字规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56005909/