gpt4 book ai didi

r - GREP : Find the locations where 2 words co-exist in a list of strings

转载 作者:行者123 更新时间:2023-12-02 06:54:51 25 4
gpt4 key购买 nike

给定以下列表:

list <- c("Horse Cat - Dog - Snake/Cow", "Monkey  Chicken - Horse - Donkey/Cow", "Fish Rat - Tortoise - Worm/Bird", "Bat Lizard - Ox - Snake/Cow",
"Dog Cat - Horse - Snake/Cow")

找到 Horse 和 Cow 在同一个字符串中的位置的最佳方法是什么?

尝试:grepl("Horse & Cow", list) 给我:[1] FALSE FALSE FALSE FALSE FALSE

如何编写返回 [1] TRUE TRUE FALSE FALSE TRUE 的 grep 语句?

最佳答案

您可以尝试使用正则表达式实现此目的,这似乎可行

grepl("Horse.*?Cow|Cow.*?Horse", list)
## [1] TRUE TRUE FALSE FALSE TRUE

如果您想忽略大小写,可以添加 ignore.case = TRUE

顺便说一句,如果你想要这些位置,最好使用 grep 而不是

grep("Horse.*?Cow|Cow.*?Horse", list)
## [1] 1 2 5

关于r - GREP : Find the locations where 2 words co-exist in a list of strings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33417784/

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