gpt4 book ai didi

r - 匹配 R 中不完全匹配的字符串

转载 作者:行者123 更新时间:2023-12-05 01:50:34 24 4
gpt4 key购买 nike

考虑以下名为 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 列向量。我很难做到这一点,因为向量中的名称与列中的名称不完全匹配。例如,我曾尝试做这样的事情:

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 中不完全匹配的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72943519/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com