Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do.call-like function for binary operators in R

Tags:

r

Is there a built-in function in R for calling binary operators/functions over a list or data frame?

Take, for example, a data frame with three logicals:

set.seed(10)
foo <- matrix(as.logical(round(runif(24))), ncol = 3)
foo <- as.data.frame(foo)

Now I would like to do something like this:

do.call.bin("|", foo)

so that it applies the or-operator to all columns, yielding:

[1]  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE

A possible implementation could be:

do.call.bin <- function (fun.bin, lst) {
    fun.bin <- match.fun(fun.bin)
    if (length(lst) > 2) {
        ret <- fun.bin(lst[[1]], Recall(fun.bin, lst[-1]))
    } else {
        ret <- fun.bin(lst[[1]], lst[[2]])
    }
    return (ret)
}

However, I doubt this isn't already implemented in R, though I haven't found it so far. Is there otherwise a more efficient way to do this?

I can't use do.call() since binary operators take only two arguments and I would like to apply a binary operator to more arguments.

like image 986
user1197460 Avatar asked Feb 14 '12 17:02

user1197460


1 Answers

For this case in particular, this would do the same trick:

> apply(foo, 1, function(x) Reduce("|", x))
[1]  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE

I'm not sure if this will generalize to whatever real problem you have in mind, but it feels like something related to Reduce is what you have in mind, no?

like image 82
Steve Lianoglou Avatar answered Oct 12 '22 22:10

Steve Lianoglou