Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify which columns are not "NA" per row in a matrix?

Tags:

r

matrix

I have a matrix with 12 rows and 77 columns, but to simply lets use:

p <- matrix(NA,5,7)  
p[1,2]<-0.3  
p[1,3]<-0.5  
p[2,4]<-0.9  
p[2,7]<-0.4  
p[4,5]<-0.6 

I want to know which columns are not "NA" per row, so what I would like to get would be something like:

[1] 2,3  
[2] 4  
[3] 0  
[4] 5  
[5] 0 

but if I do > which(p[]!="NA") I get [1] 6 11 17 24 32

I tried using a loop:

aux <- matrix(NA,5,7)  
for(i in 1:5) {  
    aux[i,]<-which(p[i,]!="NA")  
}

but I just get an error: number of items to replace is not a multiple of replacement length

Is there a way of doing this? Thanks in advance

like image 486
sbg Avatar asked Sep 16 '11 18:09

sbg


People also ask

How do you check if there is na in a column?

You can test for both by wrapping them with the function any . So any(is.na(x)) will return TRUE if any of the values of the object are NA . And any(is. infinite(x)) will return the same for -Inf or Inf .

How do I check if something is not NA in R?

To check which value in NA in an R data frame, we can use apply function along with is.na function. This will return the data frame in logical form with TRUE and FALSE.

How do I find a specific column and a row in a matrix?

R – Get Specific Column of Matrix To get a specific column of a matrix, specify the column number preceded by a comma, in square brackets, after the matrix variable name. This expression returns the required row as a vector. In this tutorial, we will learn how to get a single column from a Matrix, with examples.

How do I find columns with NA in R?

The following in-built functions in R collectively can be used to find the rows and column pairs with NA values in the data frame. The is.na() function returns a logical vector of True and False values to indicate which of the corresponding elements are NA or not.


1 Answers

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32
like image 144
IRTFM Avatar answered Sep 20 '22 14:09

IRTFM