jlk199
jlk199

Reputation: 137

Count number of items within lists within matrix R

I have two a matrix where some of the cells within the matrices are NA and others are filled with a list of numbers. And what I need is a way to calculate the number of items within each list for each cell of the matrix.

Here is the matrix:

> matrix_1
     [,1]      [,2]     
[1,] NA            c(1001, 1002)
[2,] c(1001, 1003) NA       

Here is what I am looking for:

     [,1]    [,2]     
[1,] NA      2
[2,] 2       NA     

The actual data set is much, much larger - so I am trying to avoid loops.

Here is the dput:

Matrix 1 = structure(list(NA, c(1001, 1003), c(1001, 1002), NA), .Dim = c(2L, 
2L))

Upvotes: 2

Views: 86

Answers (3)

Onyambu
Onyambu

Reputation: 79338

You could decide to do:

NA^is.na(matrix1) * lengths(matrix1)
     [,1] [,2]
[1,]   NA    2
[2,]    2   NA

or even:

 `is.na<-`(lengths(matrix1), is.na(matrix1))
     [,1] [,2]
[1,]   NA    2
[2,]    2   NA

Upvotes: 1

Dominic van Essen
Dominic van Essen

Reputation: 872

It seems that your description of the question and the expected output are slightly different.

The number of items in a list element conaining a single NA is 1, not NA. So the answer to this is:

 matrix1=matrix(list(NA,c(1001,1003),c(1001,1002),NA),nrow=2)
answer=array(lengths(matrix1),dim=dim(matrix1))
answer
#      [,1] [,2]
# [1,]    1    2
# [2,]    2    1

However, if you want to convert all the elements corresponding a single NA entry to be NA themselves (in agreement with your expected output), you can do the extra step:

answer[is.na(matrix1)]=NA
answer
#      [,1] [,2]
# [1,]   NA    2
# [2,]    2   NA

Note that elements of more-than-one item, of which some are NA won't be detected by this last step... (you'd need to use answer[sapply(matrix1,function(x) any(is.na(x)))]=NA instead).

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 102680

Maybe you can try lengths + replace like below

> replace(lengths(matrix_1),which(is.na(matrix_1)),NA)
     [,1] [,2]
[1,]   NA    2
[2,]    2   NA

Upvotes: 0

Related Questions