考虑以下名为estimates_df的数据帧.

....
                                Item            section
7596                5 Gal Samandoque      Cacti/Accents
7597       5 Gal Purple Prickly Pear      Cacti/Accents
7598              5 Gal Banana Yucca      Cacti/Accents
7599                5 Gal Yucca Vine              Vines
7600             5 Gal Red Three Awn            Grasses
7601 3/4" Screened To Match Existing      Decomposed Granite
...

我还有一个名为cactus_names的仙人掌/肉质名称的字符向量.

[1]"Prickly Pear"
[2]"Samandoque"
[3]"Banana Yucca"
...

我不想更改Item列中的全名,但我想根据我的仙人掌/肉质载体中出现的名称更改section列.我很难做到这一点,因为向量中的名称与列中的名称不完全匹配.例如,我try 过这样做:

estimates_df %>%
mutate(section = ifelse(cactus_names %in% Item, "Cacti/Succulents", section)

显然,这与任何名称都不匹配,因为它们不完全匹配.我希望最终结果是这样的:

....
                                Item            section
7596                5 Gal Samandoque      Cacti/Succulents
7597       5 Gal Purple Prickly Pear      Cacti/Succulents
7598              5 Gal Banana Yucca      Cacti/Succulents
7599                5 Gal Yucca Vine              Vines
7600             5 Gal Red Three Awn            Grasses
7601 3/4" Screened To Match Existing      Decomposed Granite
...

推荐答案

你在找这样的东西吗!

library(dplyr)
library(stringr)

cactus_names <- c("Prickly Pear", "Yucca Vine", "Banana Yucca")

pattern <- paste(cactus_names, collapse = "|")

df %>% 
  mutate(section = ifelse(str_detect(Item, pattern), "Cacti/Succulents", section))

    id                           Item            section
1 7596               5 Gal Samandoque      Cacti/Accents
2 7597      5 Gal Purple Prickly Pear   Cacti/Succulents
3 7598             5 Gal Banana Yucca   Cacti/Succulents
4 7599               5 Gal Yucca Vine   Cacti/Succulents
5 7600            5 Gal Red Three Awn            Grasses
6 7601 3/4 Screened To Match Existing Decomposed Granite

R相关问答推荐

错误:非常长的R行中出现意外符号

R-更新面内部的栅格值

在数组索引上复制矩阵时出错

如何提取所有完美匹配的10个核苷酸在一个成对的匹配与生物字符串在R?>

R Read.table函数无法对制表符分隔的数据正常工作

哪一行和行和 Select 特定行,但是考虑到Nas

如何从向量构造一系列双边公式

如何在使用箭头R包(箭头::OPEN_DATASSET)和dplyr谓词时编写具有整齐计算的函数?

如何使用FormC使简单算术运算得到的数字是正确的?

如何预测原始数据集并将值添加到原始数据集中

如何将EC50值绘制在R中的剂量-react 曲线上?

禁用时,SelecizeInput将变得不透明

策略表单连接两个非常大的箭头数据集,而不会 destruct 内存使用

随机生成样本,同时在R内的随机样本中至少包含一次所有值

在具有条件的循环中添加行

如何准确地指出Read_delim所面临的问题?

等价于Plot_ly R中的geom_函数

将一个字符串拆分成R中的两行或多行,同时复制其他列

如何覆盖R中的警告

R图不同 colored颜色 的回归线和散点图