换字规则

标签 r

我有一个这样的数据框:

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/

相关文章:

r - 在R的httr包中使用oauth2.0 token

r - 选择组合的子集

R加权算术平均数

r - 仅保留元素数量最多的 "cluster"

r - 如何删除 R Markdown 文档中的警告消息?

r - 使用合并语句时出现重复列

r - 查找分位数或查找新数据点的范围

r - 从 1 个数据帧中的多个时间序列的开头和结尾有效地删除缺失值

r - 为什么 tempdir() 在 fork 集群的每个核心上给出相同的结果?

r - 使用 r : Check existence of directory and create it if it doesn't exist 进行文件夹管理