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.
For this case in particular, this would do the same trick:
I’m not sure if this will generalize to whatever real problem you have in mind, but it feels like something related to
Reduceis what you have in mind, no?