[R] Removing Zeros from matrix
Dimitris Rizopoulos
d.rizopoulos at erasmusmc.nl
Tue Mar 9 13:53:44 CET 2010
On 3/9/2010 1:36 PM, Paul Hiemstra wrote:
> 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:
well, this way is much more efficient to compute, especially if you have
many rows. Compare the following to see the difference:
mat <- matrix(rnorm(2*1e06), 1e06, 2)
mat[sample(2*1e06, 50)] <- 0
system.time(index1 <- !apply(mat == 0, MARGIN = 1, any))
system.time(index2 <- rowMeans(mat == 0) == 0 )
all.equal(index1, index2)
Best,
Dimitris
> # 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.
>>>
>>
>
>
--
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center
Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014
More information about the R-help
mailing list