1

Let's say I have a data frame with columns of data, and I want to calculate the one-sided moving average of each column. Why does this work

my.rollapply <- function(x){

    return(rollapply(x,moving.avg,FUN= mean, fill = NA,align = 'right', na.rm = TRUE))

}

averageData <- apply(averageData, 2, my.rollapply)

but

averageData <- apply(averageData, 2, rollapply, width = moving.avg, FUN = mean, fill = NA, align = 'right', na.rm = TRUE)

gives me an error of

Error in mean.default(newX[, i], ...) : 
  'trim' must be numeric of length one

Is this because mean itself requires additional parameters? How would I be able to pass in all the parameters to rollapply inside of apply then?

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
jtanman
  • 654
  • 1
  • 4
  • 18

1 Answers1

1

Explanation:

averageData <- apply(averageData, 2, rollapply, width = moving.avg,
                     FUN = mean, fill = NA, align = 'right', na.rm = TRUE)

This won't work (and isn't a good idea) for a couple reasons (maybe more):

  1. FUN is a formal argument to both apply and rollapply.
  2. ... are are passed to rollapply and passed to mean.

Since FUN is a formal argument to apply, it's matched to the apply call and not passed via ... to the rollapply call. So your apply call is interpreted as:

apply(X=averageData, MARGIN=2, FUN=mean, rollapply, width=moving.avg,
      fill=NA, align='right', na.rm=TRUE)

Which means the mean call inside the apply loop is:

mean(tmp[,i], ...)
# which is equivalent to
mean(tmp[,i], rollapply, width=moving.avg, fill=NA, align='right', na.rm=TRUE)

Which fails because the trim argument is rollapply, which is a function, not a numeric vector of length 1.

Solution:

Regardless, the easy way to solve this problem is to use the by.column argument of rollapply:

library(xts)
data(sample_matrix)
x <- as.zoo(sample_matrix)
y <- rollmeanr(x, k=moving.avg, fill=NA, na.rm=TRUE, by.column=TRUE)
Community
  • 1
  • 1
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • Ok thanks! I'm defining the function beforehand for now, but I just wanted to better understand the structure of apply's ... Thanks for clearing it up! – jtanman Sep 12 '14 at 12:57