Search code examples
rdate-comparison

row wise comparison between a vector and a matrix in r


I have two datasets from 10 people. One is a vector, and the other is a matrix. What I want to see is if the first element of the vector includes in the first row of the matrix, and if the second element of the vector includes in the second row of the matrix, and so on.

so, I changed the vector into a matrix and used apply to compare them row-wise. But, the result was not that correct.

Here is the datasets.

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

However, the result must be all FALSE but 8th and 9th. Can anyone correct the function? Thanks!


Solution

  • Here are a few approaches you could take

    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