[R] remove NA rows and columns

Antje antje.niederlein at yahoo.de
Tue Jul 31 16:04:48 CEST 2007


Hello,

thank you both very much!
It is as easy as expected... (I think I still have to learn a lot!)

Have a nice day!
Antje



Vladimir Eremeev schrieb:
> Or, these operations can be called in one command:
> 
>> testmatrix[-which(apply(testmatrix,1,function(x)all(is.na(x)))),-which(apply(testmatrix,2,function(x)all(is.na(x))))]
>      [,1] [,2]
> [1,]    1    1
> [2,]    2    2
> [3,]    1    1
> [4,]    2    2
> 
> 
> 
> Vladimir Eremeev wrote:
>>> testmatrix
>>      [,1] [,2] [,3] [,4]
>> [1,]   NA   NA   NA   NA
>> [2,]   NA    1    1   NA
>> [3,]   NA    2    2   NA
>> [4,]   NA    1    1   NA
>> [5,]   NA    2    2   NA
>> [6,]   NA   NA   NA   NA
>>
>>> tm1<-testmatrix[,-which(apply(testmatrix,2,function(x)all(is.na(x))))]
>>> tm1
>>      [,1] [,2]
>> [1,]   NA   NA
>> [2,]    1    1
>> [3,]    2    2
>> [4,]    1    1
>> [5,]    2    2
>> [6,]   NA   NA
>>
>>> tm2<-tm1[-which(apply(testmatrix,1,function(x)all(is.na(x)))),]
>>> tm2
>>      [,1] [,2]
>> [1,]    1    1
>> [2,]    2    2
>> [3,]    1    1
>> [4,]    2    2
>>  
>>
>> Antje wrote:
>>> I guess, it's a rather simple thing but I cannot find a short way to
>>> reduce a 
>>> matrix, removing all rows and columns having just NA elements.
>>>
>>> testmatrix <- matrix(nrow=6, ncol=4)
>>> testmatrix[2:5,2:3] <- seq(2)
>>>
>>>  > testmatrix
>>>       [,1] [,2] [,3] [,4]
>>> [1,]   NA   NA   NA   NA
>>> [2,]   NA    1    1   NA
>>> [3,]   NA    2    2   NA
>>> [4,]   NA    1    1   NA
>>> [5,]   NA    2    2   NA
>>> [6,]   NA   NA   NA   NA
>>>
>>> the new matrix should look like this (by the way, I don't "know" which
>>> rows and 
>>> columns are the one to be deleted...
>>>
>>>  > testmatrix
>>>       [,1] [,2]
>>> [1,]   1    1
>>> [2,]   2    2
>>> [3,]   1    1
>>> [4,]   2    2
>>>
>>
>



More information about the R-help mailing list