I have a matrix (V), which looks like this
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[V1,] 37 15 30 3 4 11 35 31
[V2,] 44 31 45 30 24 39 1 18
[V3,] 39 49 7 36 14 43 26 24
[V4,] 45 31 26 33 12 47 37 15
[V5,] 23 27 34 29 30 34 17 4
[V6,] 9 46 39 34 8 43 42 37
I have another matrix (X)
[,1] [,2] [,3] [,4] [,5] [,6]
[X1,] 37 15 21 3 4 11 35 31
[X2,] 37 37 45 30 24 39 1 18
[X3,] 39 49 7 36 14 43 26 24
[X4,] 45 31 26 37 12 47 37 15
[X5,] 23 27 34 29 30 37 17 4
[X6,] 9 46 39 34 8 37 42 37
Now each row of matrix V should be matched with each row of matrix X to get a count matrix like
[,V1] [,V2] [,V3] [,V4] [,V5] [,V6] [,V7] [,8]
[X1,] 7
[X2,]
To check the common numbers between X1 and V1??
How do I do it using R? Please suggest me some ideas
Here is one quick 'brute-force' way with apply
row.names(V) <- paste0("V",seq(6))
row.names(X) <- paste0("X",seq(6))
apply(V, 1, function(i){
apply(X, 1, function(j){
length(intersect(i, j))
}
)
})
V1 V2 V3 V4 V5 V6
X1 7 1 0 3 1 1
X2 2 6 2 2 1 2
X3 0 2 8 1 0 2
X4 3 2 1 7 0 1
X5 3 1 0 1 7 2
X6 1 1 1 1 1 7
Use == to compare the elements of the two matrices. This will give you a matrix of logicals (TRUEs and FALSEs). You can then add up the the number of TRUEs in each row using apply().
apply(V==X, 1, sum)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.