[R] Deleting rows or cols that do not meet cut off

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Tue Apr 21 23:40:53 CEST 2009


Rolf Turner wrote:
>
> On 22/04/2009, at 8:34 AM, Crosby, Jacy R wrote:
>
>> How can I delete both rows and columns that do not meet a particular
>> cut off value.
>> Example:
>>> d <- rbind(c(0,    1,    6,    4),
>> + c(2,    5,   7,    5),
>> + c(3,    6,    1,    6),
>> + c(4,    4,    4,    4))
>>> f <- as.matrix(d)
>>> f
>>      [,1] [,2] [,3] [,4]
>> [1,]    0    1    6    4
>> [2,]    2    5    7    5
>> [3,]    3    6    1    6
>> [4,]    4    4    4    4
>>
>> I would like to delete all rows and columns that do not contain at
>> least one element with a value less than 1.
>
>     Apparently you actually want ``less than or equal to 1''.
>
>> So I'd end up with:
>>
>>> f
>>      [,1] [,2] [,3]
>> [1,]    0    1    6
>>  [3,]    3    6    1
>>
>> Note: 1 is an arbitrary cut-off value.
>
> d[apply(d,1,function(x){any(x<=1)}),apply(d,2,function(x){any(x<=1)})]

... or gain a bit on performance by doing the threshold comparison on
the whole matrix just once at once:

    dd = d <= 1
    d[apply(d, 1, any), apply(d, 2, any)]

vQ




More information about the R-help mailing list