[R] Using apply for logical conditions

Allan Engelhardt allane at cybaea.com
Mon Aug 2 22:43:02 CEST 2010


`|` is a binary operator which is why the apply will not work.  See

help("Reduce")

For example,

set.seed(1)
data <- data.frame(A = runif(10) > 0.5, B = runif(10) > 0.5, C = 
runif(10) > 0.5)
Reduce(`|`, data)
#  [1]  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE

Hope this helps.

Allan

On 02/08/10 21:35, Alastair wrote:
> Hi,
>
> I've got some boolean data in a data.frame in the form:
>        X    Y    Z    A   B   C
> [1]  T     T    F    T   F   F
> [2]  F     T    T    F   F   F
> .
> .
> .
>
>
> What I want to do is create a new column which is the logical disjunction of
> several of the columns.
> Just like:
>
> new.column<- data$X | data$Y | data$Z
>
> However I don't want to hard code the particular columns into the expression
> like that. I've tried using apply row wise with `|` as the function:
>
> columns<- c(X,Y,Z)
> apply(data[,columns], 1,`|`)
>
> This doesn't seem to do what I would have expected, does anyone have any
> advice how to use the the apply or similar function to perform a boolean
> operation on each row (and a specific subset of the columns) in a data
> frame?
>
> Thanks,
> Alastair
>
>
>



More information about the R-help mailing list