Wakan Tanka
Wakan Tanka

Reputation: 8052

calling rollapply for each column of matrix using apply

I have this matrix:

> mtrx <- matrix(c(1:30), nrow=10)
> mtrx
      [,1] [,2] [,3]
 [1,]    1   11   21
 [2,]    2   12   22
 [3,]    3   13   23
 [4,]    4   14   24
 [5,]    5   15   25
 [6,]    6   16   26
 [7,]    7   17   27
 [8,]    8   18   28
 [9,]    9   19   29
[10,]   10   20   30
> is.matrix(mtrx)
[1] TRUE

I can apply function (in this case mean) to each column this way:

> apply(mtrx, 2, mean)
[1]  5.5 15.5 25.5

I can also use rollapply function to specific column (in this case 1st)

> require(zoo)
> rollapply(mtrx[,1], width = 2, by = 2, FUN = mean, align = "left")
[1] 1.5 3.5 5.5 7.5 9.5

How can combine above approaches and execute rollapply over each matrix column? I've tried following:

> apply(mtrx, 2, rollapply, width = 2, by = 2, FUN = mean, align = "left")
Error in mean.default(newX[, i], ...) : 
  'trim' must be numeric of length one

And also method suggested here:

> apply(mtrx, 2, function(x) rollapply(width = 2, by = 2, FUN = mean, align = "left"))
Error in index(x) : argument "data" is missing, with no default

but both gives me an error which I do not understand.

Upvotes: 0

Views: 874

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 270448

Moved from comments.

You don't need apply. rollapply already acts on each column of a matrix by default:

rollapply(mtrx, width = 2, by = 2, FUN = mean, align = "left")

See ?rollapply

Also, the reason your code does not work is that FUN=mean is being regarded as the function passed to apply, not the function passed to rollapply.

Upvotes: 1

Related Questions