[R] Removing Zeros from matrix

Paul Hiemstra p.hiemstra at geo.uu.nl
Tue Mar 9 13:36:27 CET 2010


Dimitris Rizopoulos wrote:
> one approach is the following:
>
> mat <- matrix(rnorm(100*45), 100, 45)
> mat[sample(100*45, 50)] <- 0
>
> index <- rowMeans(mat == 0) == 0
> mat[index, ]
Dimitris,

You use quite a complicated syntax to get the index. I think the 
following syntax using apply is more easy to understand:

# Note, MARGIN equal to 1 means loop over rows
# If any member of a row is zero
index = apply(mat == 0, MARGIN = 1, any)
# If all members of a row are zero
index = apply(mat == 0, MARGIN = 1, all)

cheers and hope it helps,
Paul
>
>
> I hope it helps.
>
> Best,
> Dimitris
>
>
> On 3/9/2010 11:05 AM, ogbos okike wrote:
>> Hi Everybody,
>> I have a matrix of about 45 columns. Some of the rows contain zeros. 
>> Using
>>> data1<-data[complete.cases(data),], I can remove the "NA" rows. But 
>>> I am
>> unable to tackle that of zeros.
>> Can anybody give me an idea of how to remove rows containing zeros in a
>> matrix.
>> Thanks so much
>> Best
>> Ogbos
>>
>> [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide 
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>


-- 
Drs. Paul Hiemstra
Department of Physical Geography
Faculty of Geosciences
University of Utrecht
Heidelberglaan 2
P.O. Box 80.115
3508 TC Utrecht
Phone:  +3130 274 3113 Mon-Tue
Phone:  +3130 253 5773 Wed-Fri
http://intamap.geo.uu.nl/~paul



More information about the R-help mailing list