gpt4 book ai didi

R - 测试字符串向量是否包含另一个列表的任何元素

转载 作者:行者123 更新时间:2023-12-02 05:47:29 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Matching multiple patterns

(6 个回答)


3年前关闭。




我有:

> lst_A <- c("TET","RNR")
> DT_result <- data.table(lst_B = c("RNR_B","BC_TET"))

我想要:
> DT_result <- data.table(lst_B = c("RNR_B","BC_TET"), result = c(TRUE,TRUE))
> DT_result
lst_B result
1: RNR_B TRUE
2: BC_TET TRUE

基本上,对于 'lst_B' 中的每个元素,如果它包含 'lst_A' 中的任何元素,则为 TRUE,否则为 FALSE。

最佳答案

您可以使用 grepl 获得此信息.

lst_A <- c("TET","RNR")
lst_B = c("RNR_B","BC_TET")

Pattern = paste(lst_A, collapse="|")
grepl(Pattern, lst_B)

library(data.table)
DT_result <- data.table(lst_B, result=grepl(Pattern, lst_B))
DT_result
lst_B result
1: RNR_B TRUE
2: BC_TET TRUE

添加

为了回复评论,这里有一个包含更多要测试的字符串的示例。有些通过了测试,有些则没有。
lst_A <- c("TET","RNR")
lst_B = c("RNR_B","BC_TET", "Fred", "RNR_A", "Zero", "ABC_TET")

Pattern = paste(lst_A, collapse="|")

DT_result <- data.table(lst_B, result=grepl(Pattern, lst_B))
DT_result
lst_B result
1: RNR_B TRUE
2: BC_TET TRUE
3: Fred FALSE
4: RNR_A TRUE
5: Zero FALSE
6: ABC_TET TRUE

关于R - 测试字符串向量是否包含另一个列表的任何元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50672316/

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