如何检查数据框中是否包含列表或向量的任何值?

时间:2017-09-21 09:46:05

标签: r regex

我有一个带有一些全名的数据框和一个带名字的向量:

d <- data.frame(myName = c("Adam Smith","John Smith","John Clarks "))

first <- c("Adam","Mark","Jim")

我需要检查来自&#34; first&#34;包含在&#34; d&#34;的每一行中,因此结果应如下所示:

Adam Smith  TRUE
John Smith  FALSE
John Clarks FALSE

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

您可以使用grepl()

d <- data.frame(full_names = c("Adam Smith","John Smith","John Clarks "))

first <- c("Adam","Mark","Jim")

d$check <- grepl(paste0(first, collapse = "|"), d$full_names)

d
    full_names check
1   Adam Smith  TRUE
2   John Smith FALSE
3 John Clarks  FALSE