[R] A function like sum but with functions other than '+'

Julio Sergio juliosergio at gmail.com
Mon Apr 2 00:25:14 CEST 2012


Because I didn't find in R any functions similar to the function 'reduce' from 
Python, I'm writing a function "freduce" as follows:

freduce <- function(f, vec, ValIni=NULL, StopIn=NULL) {
  # f: is any function that takes two arguments of the same type
  # vec: is a vector of n values accepted by 'f'
  # 
  # Initially f starts with ValIni, if it's given or the first element 
  # of 'vec', and then applies sequentially f to that value and one of the
  # elements of 'vec', leaving the result as the first argument of 'f' for
  # the next application of the function.
  #
  # If StopIN is given, the result is compared with this value to stop the
  # operation and return such a value.

  # Detects if ValIni was given:
  r <- if (is.null(ValIni)) c(2,vec[1]) else c(1,ValIni)
  for (e in vec[r[1]:length(vec)]) {
    if (!is.null(StopIn) && r[2] == StopIn) return (StopIn)
    r[2] <- do.call(f, list(r[2],e))
  }
  return(r[2])
}

When this function is called with '+' and a vector of numbers, it behaves 
exactly as sum

* freduce('+', c(3.5, 2.7, -1))
[1] 5.2
* sum(c(3.5, 2.7, -1))
[1] 5.2

But, then, you can call it with other operators; for instance, a generalized 
'or' or 'and' operation, optionally stoping the operation when the value is 
determined:

* freduce('|', c(0,0,1,0,0,1), StopIn=T)
[1] TRUE
* freduce('&', c(0,0,1,0,0,1), StopIn=F)
[1] FALSE

My question is if there exists a way to do this more directly in R?

Thanks,

--Sergio.



More information about the R-help mailing list