[R] Using apply for logical conditions
Joshua Wiley
jwiley.psych at gmail.com
Mon Aug 2 22:48:10 CEST 2010
In addition to Reduce(), you can take a look at ?any for '|' and ?all for '&'.
Josh
On Mon, Aug 2, 2010 at 1:43 PM, Allan Engelhardt <allane at cybaea.com> wrote:
> `|` 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
>>
>>
>>
>
> ______________________________________________
> 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.
>
--
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/
More information about the R-help
mailing list