Skip to content
All library documents

How rollapply’s by.column Option Works on Matrices

Article Quant Q&A · Author: Nour

Summary

The document compares two outputs from R’s rollapply function when applied to a matrix with a rolling width of three. With by.column set to TRUE, the function applies the requested operation separately to each column, producing a rolling mean down each column. The first two rows are filled with missing values because a full three-row window is not yet available; subsequent rows show the means for each column’s trailing window.

With by.column set to FALSE, the operation receives the rolling window across the matrix as a whole rather than being run independently on each column. In the example, mean therefore returns one value per window, yielding a vector instead of a matrix. The document presents example output but no broader discussion of other functions, irregular windows, or alternative arguments. The key choice is whether the callback should see each column’s window independently or the full rolling slice together.

Key ideas

  • With by.column set to TRUE, rollapply applies the function independently to each matrix column.
  • With by.column set to FALSE, the function receives each rolling slice across the matrix as a whole.
  • For a three-row trailing window, the first two output rows are missing because the window is incomplete.
  • The choice of setting determines whether the result is column-wise or computed from each full matrix window.

Tags

Full text
# Rollapply: what does by.column do?


# Rollapply: what does by.column do?












I have read the description of by.column for rollapply in the manual but i couldn't understand how to use it. see below:

x=matrix(1:60,nrow=10)

rollapply(x,3,mean,fill=NA,align="right",by.column=FALSE)

```
 [1] NA NA 27 28 29 30 31 32 33 34
```

when i use by.column= FALSE: it applies mean to width (3) rolling number of lines mean(x[1:3,])

now, if i use by.column=TRUE then i get:

x=matrix(1:60,nrow=10)

rollapply(x,3,mean,fill=NA,align="right",by.column=TRUE)

```
     [,1] [,2] [,3] [,4] [,5] [,6]

[1,]  NA   NA   NA   NA   NA   NA

[2,]  NA   NA   NA   NA   NA   NA

[3,]  2   12   22   32   42   52

[4,]  3   13   23   33   43   53

[5,]  4   14   24   34   44   54

[6,]  5   15   25   35   45   55

[7,]  6   16   26   36   46   56

[8,]  7   17   27   37   47   57

[9,]  8   18   28   38   48   58

[10,] 9   19   29   39   49   59
```

i can't make sense of the result. could anyone please explain what's the use of by.column and maybe provide an example? Thanks

Shown in full with attribution under the source's licence. Licence: CC BY-SA 4.0 (Stack Exchange)

This summary was written by Stratmill's research agent from the original; it is not a copy of the source.