Skyie
Skyie

Reputation: 23

Finding the count of the same matrix and ignoring NAs present in the matrix

I have a matrix (V), which looks like this

       [,1] [,2] [,3]
[V1,]    37   15   NA
[V2,]    44   31   NA
[V3,]    NA   37   56

When [V1,] is compared to itself, the count is 2, as the two numbers are matched.

When [V1,] is compared to [V2,], the count is 0, because none of the numbers are matched.

Now each row of matrix V should be matched with itself (V) to get a count matrix like

     [,V1] [,V2] [,V3]
[V1,]    2     0     1
[V2,]    0     2     0
[V3,]    1     0     2

So, it is to count number of elements in a vector that are not NA..

To check the count between two same matrices (V==V)?

I have posted almost the same question here

Finding pattern in one matrix to another matrix in R

But I don't know how to do the same without counting NA in the matrices?

How do I do it using R?

Upvotes: 1

Views: 103

Answers (4)

akrun
akrun

Reputation: 887531

Another option would be using the row index as 'X' and 'Y' arguments in outer, Vectorize the operation, subset the rows of 'V' based on the index, check whether the non-NA (na.omit) elements are present (%in%) in the rows that are compared, and get the sum. The output will be matrix and the length of that depends on the prod(dim(V))

 outer(1:nrow(V), 1:nrow(V), 
    FUN=Vectorize(function(i, j) sum(na.omit(V[i,]) %in% na.omit(V[j,]))) )
 #     [,1] [,2] [,3]
 #[1,]    2    0    1
 #[2,]    0    2    0
 #[3,]    1    0    2

data

  V <- matrix(c(37,44, NA, 15, 31, 37, NA, NA, 56), ncol=3)

Upvotes: 3

RHertel
RHertel

Reputation: 23798

This gives the desired result:

mat2 <- V
for(i in 1:nrow(V)){
  for (j in 1:nrow(V)) mat2[i,j] <- sum(na.omit(V[i,]) %in% (na.omit(V[j,])))
}
> mat2
#     [,1] [,2] [,3]
#[1,]    2    0    1
#[2,]    0    2    0
#[3,]    1    0    2

data

V <- matrix(c(37,15,NA,44,31,NA,NA,37,56),ncol=3, byrow=T)

Upvotes: 4

Gaurav
Gaurav

Reputation: 1587

You can use the use the following code to get the count of matching elements in two rows excluding NAs...

length(na.omit(intersect(V[i,],v[j,])))

You can put this in a loop to generate a matrix.

Upvotes: 2

Lars Lau Raket
Lars Lau Raket

Reputation: 1974

You can also go with a good old double-apply:

V <- matrix(c(37, 15, NA, 44, 31, NA, NA, 37, 76), 3, byrow = TRUE)
compare <- function(V1, V2) sum(na.omit(V1) %in% na.omit(V2))
apply(V, 1, function(V1) apply(V, 1, function(V2) compare(V1, V2)))

Upvotes: 2

Related Questions