Search code examples
rfunctionarguments

Passing function as argument in R


I am trying to pass a customisable function as argument in R in the following function:

moving_window_filter2 <- function(vec, deltan, FUN = "min") {
  spectrum <- vec
  n <- length(vec)
  for (i in 1:n) {
    nmin <- max(1, i - deltan/2)
    nmax <- min(n, i + deltan/2)
    spectrum[i] <- FUN(vec[nmin:nmax])
  }
  return(spectrum)
}

However, this code results in an error saying that Error in FUN(vec[nmin:nmax]) : could not find function "FUN". What should I do?

Many thanks.


Solution

  • As stated in the comments, you are mixing passing the function by name and then trying to apply it as the actual function object.

    Use do.call. It accepts either.

    moving_window_filter2 <- function(vec, deltan, FUN = "min") {
      spectrum <- vec
      n <- length(vec)
      for (i in 1:n) {
        nmin <- max(1, i - deltan/2)
        nmax <- min(n, i + deltan/2)
        spectrum[i] <- do.call(FUN, list(vec[nmin:nmax]))
      }
      return(spectrum)
    }