在R中,对一个向量和一个矩阵进行逐行比较。

4
我有来自10个人的两个数据集。一个是向量,另一个是矩阵。我想要看到的是向量的第一个元素是否包含在矩阵的第一行中,第二个元素是否包含在矩阵的第二行中,以此类推。
因此,我将向量转换为矩阵,并使用apply按行进行比较。但结果并不正确。
以下是数据集。
df1<-matrix(c(rep(0,10),2,4,7,6,5,7,4,2,2,2),ncol=2)
df1
#      [,1] [,2]
# [1,]    0    2
# [2,]    0    4
# [3,]    0    7
# [4,]    0    6
# [5,]    0    5
# [6,]    0    7
# [7,]    0    4
# [8,]    0    2
# [9,]    0    2
#[10,]    0    2

df2<-c(1,3,6,4,1,3,3,2,2,5)
df2<-as.matrix(df2)
apply(df2, 1, function(x) any(x==df1))
# [1] FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE  TRUE  TRUE  TRUE

然而,结果必须全部为FALSE,除了第8和第9个。 有人能够更正这个函数吗?谢谢!
2个回答

7
这个向量化的代码应该非常高效:
> as.logical( rowSums(df1==df2))
 [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE FALSE

1
这应该是被接受的答案。我总是忘记矩阵是按列填充/比较的。 - thelatemail
我得到了 Error in df1 == df2 : non-conformable arrays,你知道为什么吗? - slamballais
1
因为df2是数据框并且具有维度。as.logical(rowSums(df1==as.numeric(df2)))应该可以工作。 - Karolis Koncevičius

5
这里有几种可能的方法:
  1. Two calls to apply

    # 
    # 1 by column to check if the values are equal
    # then by row to see if any rows contain TRUE
    apply(apply(df1,2,`==`,df2),1,any)
    
  2. Use sapply and seq_along

    sapply(seq_along(df2), function(x, y, i) y[i] %in% x[i, ], y = df2 ,x = df1)
    
  3. repeat df2 to the same length as df1 and then compare

     rowSums(df1==rep(df2, length = length(df1))) > 0
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接