一个单元格包含在 R 中的另一个单元格中

One cell is contained in another cell in R

我有类似的东西:

One       Two 
A,B,C       A 
A,C,        Z 
R,F,        K 
T           T  

如果 'Two' 包含在 'One' 中,我想加入 'Third' yes/no。

One       Two    Three
A,B,C       A     yes
A,C,        Z     no 
R,F,        K     no 
T           T     yes  

我知道我可以通过使用 grepl 来获取它,就像这样: grepl("A" , all$One) -> all&Three。但是我有几百个案例,所以我无法写出所有这些单独的查询。
那么我应该如何将整个 'Two' 单元格实现为 grepl 函数中的模式?

您可以使用stringr::str_detect

library(tidyverse)
df %>%
    mutate_if(is.factor, as.character) %>%
    mutate(Three = str_detect(One, Two))
#    One Two Three
#1 A,B,C   A  TRUE
#2  A,C,   Z FALSE
#3  R,F,   K FALSE
#4     T   T  TRUE

示例数据

df <- read.table(text  =
    "One       Two
A,B,C       A
A,C,        Z
R,F,        K
T           T", header = T)

您可以使用 mapply():

all <- read.table(header=TRUE, stringsAsFactors = FALSE, text=
"One       Two 
A,B,C       A 
A,C,        Z 
R,F,        K 
T           T")
all$Three <- mapply(grepl, all$Two, all$One)
all
# > all
#     One Two Three
# 1 A,B,C   A  TRUE
# 2  A,C,   Z FALSE
# 3  R,F,   K FALSE
# 4     T   T  TRUE

如果你真的想要 "yes" 或 "no" 作为结果,那么你可以这样做:

all$Three <- ifelse(mapply(grepl, all$Two, all$One), "yes", "no")

或(如 Rui Barradas 评论,thx):

all$Three <- factor(mapply(grepl, all$Two, all$One), labels = c("no", "yes"))