R 如何查找列和数据帧之间的匹配?

R 如何查找列和数据帧之间的匹配?,r,dataframe,R,Dataframe,我最近发布了一个问题,似乎不是很清楚,我不能删除它,因为有一个答案。在这里,我提出了一个明确的问题 我有一个如下所示的数据框 M<- structure(list(V1 = structure(c(6L, 2L, 4L, 8L, 7L, 3L, 1L, 5L ), .Label = c("203797_at", "205217_at", "211488_s_at", "211900_x_at", "213959_s_at", "217077_s_at", "219884_at", "22

我最近发布了一个问题,似乎不是很清楚,我不能删除它,因为有一个答案。在这里,我提出了一个明确的问题 我有一个如下所示的数据框

M<- structure(list(V1 = structure(c(6L, 2L, 4L, 8L, 7L, 3L, 1L, 5L
), .Label = c("203797_at", "205217_at", "211488_s_at", "211900_x_at", 
"213959_s_at", "217077_s_at", "219884_at", "220473_s_at"), class = "factor"), 
    V2 = structure(c(8L, 6L, 4L, 2L, 7L, 1L, 5L, 3L), .Label = c("202498_s_at", 
    "203313_s_at", "204407_at", "207022_s_at", "212030_at", "218566_s_at", 
    "220926_s_at", "222204_s_at"), class = "factor"), V3 = structure(c(7L, 
    2L, 8L, 1L, 3L, 6L, 4L, 5L), .Label = c("201368_at", "201502_s_at", 
    "202211_at", "202422_s_at", "206542_s_at", "212902_at", "215509_s_at", 
    "215716_s_at"), class = "factor"), V4 = structure(c(2L, 4L, 
    7L, 6L, 5L, 1L, 3L, 8L), .Label = c("203736_s_at", "204442_x_at", 
    "205882_x_at", "207317_s_at", "208138_at", "213731_s_at", 
    "215743_at", "218513_at"), class = "factor"), V5 = structure(c(7L, 
    5L, 1L, 4L, 2L, 3L, 8L, 6L), .Label = c("202052_s_at", "203809_s_at", 
    "206319_s_at", "206590_x_at", "208382_s_at", "216133_at", 
    "219736_at", "221818_at"), class = "factor")), .Names = c("V1", 
"V2", "V3", "V4", "V5"), class = "data.frame", row.names = c(NA, 
-8L))
如果一个字符存在1,如果不是零,这里有一个解决方案:

> apply(M, 2, function(col)as.numeric(col%in%t(T)))

     V1 V2 V3 V4 V5
[1,]  1  0  0  0  0
[2,]  1  0  0  0  0
[3,]  1  0  0  0  0
[4,]  1  0  0  0  0
[5,]  1  0  0  0  0
[6,]  1  0  0  0  0
[7,]  1  0  0  0  0
[8,]  1  0  0  0  0

不漂亮,但它很管用

sapply(1:ncol(M),function(i) sapply(T,function(t) t %in% M[,i]))*1

删除“*1”以获得逻辑矩阵。

我没有想到
*1
!较短的版本可以是
apply(M,2,`%in%`,t(t))*1
@PeterK我喜欢你的解决方案我喜欢你的解决方案另一个选项是
mapply('%in%',M,list(t$V1))+0L
这是什么意思?仅当
T
中的每个元素都存在于
M
中时,才检查此处的所有答案。没有人比较第一个角色…@David Arenburg如果你知道更好的方法,那就说吧,我很想看到它我说我不明白这个问题。“T的第一宪章”是什么意思?@David Arenburg T由8个观察组成,它们要么存在于M中,要么不存在,如果存在,那么1如果不存在,那么0
    [,1] [,2] [,3] [,4] [,5]
[1,]    1    0    0    0    0
[2,]    1    0    0    0    0
[3,]    1    0    0    0    0
[4,]    1    0    0    0    0
[5,]    1    0    0    0    0
[6,]    1    0    0    0    0
[7,]    1    0    0    0    0
[8,]    1    0    0    0    0
> apply(M, 2, function(col)as.numeric(col%in%t(T)))

     V1 V2 V3 V4 V5
[1,]  1  0  0  0  0
[2,]  1  0  0  0  0
[3,]  1  0  0  0  0
[4,]  1  0  0  0  0
[5,]  1  0  0  0  0
[6,]  1  0  0  0  0
[7,]  1  0  0  0  0
[8,]  1  0  0  0  0
sapply(1:ncol(M),function(i) sapply(T,function(t) t %in% M[,i]))*1