Allen Wang
Allen Wang

Reputation: 2502

Removing rows and columns which contain all NaN rows in a matrix

I have data in the format of

     [,1] [,2] [,3] 
[1,]    2    NaN    7 
[2,]    NaN  NaN    NaN 
[3,]    3    NaN    2

I want to remove row 2 and column 2. when I tried

mat <- mat[complete.cases(mat)]

it deletes all cases (since none of them are complete).

Is there a simple way to do this, besides replacing the NaN with zeros and doing some math on zero sum columns, and then the same for rows?

Upvotes: 0

Views: 744

Answers (3)

T. Scharf
T. Scharf

Reputation: 4834

In this case your NaN's are symmetrically placed leaving you with a nice 2 x 2 residual matrix. This might not always be the case.

What you need to do really takes two moves(locate non-NaN's, then rebuild new matrix) but can be combined into a reasonable one-liner.

newMat <- matrix( mat[!is.na(mat)], nrow=2 ,  ncol=2)

Note that we are building our new matrix column-wise from the resulting vector when we index the NaN's. There is no getting around the fact we are gonna have to build a second matrix from scratch. Our new matrix will not 'fall' into place via gravity.

Upvotes: 0

akrun
akrun

Reputation: 887251

Try this

mat[rowSums(!is.nan(mat))>0,]
#    [,1] [,2] [,3]
#[1,]    2  NaN    7
#[2,]    3  NaN    2

 mat[,colSums(!is.nan(mat))>0]
 #     [,1] [,2]
 #[1,]    2    7
 #[2,]  NaN  NaN
 #[3,]    3    2

when combined

mat[rowSums(!is.nan(mat))>0,colSums(!is.nan(mat))>0]
#     [,1] [,2]
#[1,]    2    7
#[2,]    3    2

data

mat <- matrix(c(2, NaN, 3, NaN, NaN, NaN, 7, NaN, 2), ncol=3)

Upvotes: 3

Philippe Chavanne
Philippe Chavanne

Reputation: 344

This should work:

mat <- mat[-2,-2]

Upvotes: 0

Related Questions