Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 520
Shinzi Katoh Avatar asked Dec 15 '22 08:12

Shinzi Katoh


1 Answers

This vectorized code should be very efficient:

> as.logical( rowSums(df1==df2))
 [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE FALSE
like image 117
IRTFM Avatar answered Jan 05 '23 07:01

IRTFM