0

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.

Community
  • 1
  • 1
Wakan Tanka
  • 7,542
  • 16
  • 69
  • 122
  • As regarding to the error both- `apply` and `rollapply` have a `FUN` argument, so you are specifying `FUN` for `apply` instead of `rollapply` and hence all the arguments are being passed to the `mean` function instead to the `rollapply` function- hence the error comes from `mean` (`trim` is one of its arguments). – David Arenburg Mar 10 '16 at 14:17
  • @G.Grothendieck and @DavidArenburg OK, I do not need to use `apply` I understand. Anyway how to pass arguments to `rollapply` instead of `apply` and how to make `rollapply` operate over matrix rows instead of columns (is `t()` one possible solution)? I'm asking because if knew the answer to my original question then I can easy achieve those two goals. Thank you. – Wakan Tanka Mar 10 '16 at 14:47
  • 1
    If you want to operate on row, set the `MARGIN` to 1. And in your case you will need to write an anonymous function such as `apply(mtrx, 1, function(x) rollapply(x, width = 2, by = 2, FUN = mean, align = "left"))` (similar to your last attempt, you just forgot to pass `x` to `rollapply`. Though maybe the `rollapply` offers a built in solution, IDK. Better read the documentations of `?rollapply` as pointed out. – David Arenburg Mar 10 '16 at 15:20

1 Answers1

1

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.

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341