gpt4 book ai didi

r - R 中的 grepl 查找与任何字符串列表的匹配项

转载 作者:行者123 更新时间:2023-12-03 22:48:40 25 4
gpt4 key购买 nike

在引用值列表时是否可以使用 grepl 参数,也许使用 %in% 运算符?我想获取下面的数据,如果动物名称中有“狗”或“猫”,我想返回某个值,比如“保持”;如果它没有“狗”或“猫”,我想返回“丢弃”。

data <- data.frame(animal = sample(c("cat","dog","bird", 'doggy','kittycat'), 50, replace = T))

现在,如果我只是通过严格匹配值来做到这一点,比如“猫”和“狗”,我可以使用以下方法:
matches <- c("cat","dog")

data$keep <- ifelse(data$animal %in% matches, "Keep", "Discard")

但是使用 grep 或 grepl 仅指列表中的第一个参数:
data$keep <- ifelse(grepl(matches, data$animal), "Keep","Discard")

返回
Warning message:
In grepl(matches, data$animal) :
argument 'pattern' has length > 1 and only the first element will be used

请注意,我在搜索中看到了这个线程,但这似乎不起作用:
grep using a character vector with multiple patterns

最佳答案

您可以在 | 的正则表达式中使用“或”( grepl )语句.

ifelse(grepl("dog|cat", data$animal), "keep", "discard")
# [1] "keep" "keep" "discard" "keep" "keep" "keep" "keep" "discard"
# [9] "keep" "keep" "keep" "keep" "keep" "keep" "discard" "keep"
#[17] "discard" "keep" "keep" "discard" "keep" "keep" "discard" "keep"
#[25] "keep" "keep" "keep" "keep" "keep" "keep" "keep" "keep"
#[33] "keep" "discard" "keep" "discard" "keep" "discard" "keep" "keep"
#[41] "keep" "keep" "keep" "keep" "keep" "keep" "keep" "keep"
#[49] "keep" "discard"

正则表达式 dog|cat告诉正则表达式引擎查找 "dog""cat" ,并返回两者的匹配项。

关于r - R 中的 grepl 查找与任何字符串列表的匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25391975/

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