Hey,
Thanks for your great inputs. While "index = apply(mat == 0, MARGIN = 1,
any)" gives you an idea of the rows containing zero(s),
"index<-data[!apply(data==0,MARGIN=1,any),]" does the actual job of
removing
the rows with zeros.
Kind regards
Ogbos
On 9 March 2010 15:12, Paul Hiemstra <p.hiemstra@geo.uu.nl> wrote:
> Dimitris Rizopoulos wrote:
>
>>
>>
>> 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)
>>
> Point taken, I totally agree that for large matrices you should use your
> approach. Didn't know that it made such a difference, great to learn
> something new :). But I still like the other syntax more ;).
>
> cheers,
> Paul
>
>
>>
>> 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@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 <http://intamap.geo.uu.nl/%7Epaul>
>
>
[[alternative HTML version deleted]]