[R] Using apply for logical conditions

Erik Iverson eriki at ccbr.umn.edu
Mon Aug 2 22:44:51 CEST 2010



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,`|`)
> 

Please provide *reproducible* examples.  I cannot run any of your code 
since you don't give us the objects X, Y, or Z.  An easy way to do this 
is to use ?dput on the objects we need to run your code, e.g., your 
data.frame.

Does this do what you want?

df1 <- data.frame(x = sample(c(TRUE, FALSE), 10, replace = TRUE),
                   y = sample(c(TRUE, FALSE), 10, replace = TRUE),
                   z = sample(c(TRUE, FALSE), 10, replace = TRUE))

columns <- c("x", "y", "z")

apply(df1[columns], 1, any)



More information about the R-help mailing list