Search code examples
rdata.tablerollapply

rollapplyr() creates only one new column instead of multiple columns for each column in .SDcols


I am trying to use rollapplyr() on a data table an use it to generate various columns via .SDcols. Rather than putting the results for one column next to the results for another column, however, rollapplyr() stacks the results for each column below one another. Below some code to illustrate what I mean:

library(data.table)
library(zoo)

cars <- data.table(mtcars)[, c('cyl', 'mpg', 'hp')]
setorder(cars, cyl)
maCols <- c('mpg_ma', 'hp_ma')
cars[, rollapplyr(.SD, mean, width = 3, align = 'right', partial = TRUE), 
     by = cyl, 
     .SDcols = c('mpg', 'hp')]

This code generates a data.table of two columns (cyl and V1) of 64 rows rather than a data table of three columns (cyl, V1 and V2) of 32 columns. Is there a way to obtain the latter?


Solution

  • You could try:

    cars[, lapply(.SD, function(x) rollapplyr(x, mean, width = 3, align = 'right', partial = TRUE)), 
         by = cyl, 
         .SDcols = c('mpg', 'hp')]
    

    Output:

        cyl      mpg        hp
     1:   4 22.80000  93.00000
     2:   4 23.60000  77.50000
     3:   4 23.33333  83.33333
     4:   4 26.53333  74.33333
     5:   4 28.53333  71.00000
     6:   4 32.23333  61.00000
     7:   4 28.60000  71.33333
     8:   4 27.56667  76.00000
     9:   4 24.93333  84.66667
    10:   4 27.90000  90.00000
    11:   4 25.93333 104.33333
    12:   6 21.00000 110.00000
    13:   6 21.00000 110.00000
    14:   6 21.13333 110.00000
    15:   6 20.16667 108.33333
    16:   6 19.56667 112.66667
    17:   6 18.36667 117.00000
    18:   6 18.90000 140.33333
    19:   8 18.70000 175.00000
    20:   8 16.50000 210.00000
    21:   8 16.46667 200.00000
    22:   8 16.00000 201.66667
    23:   8 16.30000 180.00000
    24:   8 14.30000 188.33333
    25:   8 12.00000 200.00000
    26:   8 11.83333 216.66667
    27:   8 13.53333 198.33333
    28:   8 15.13333 176.66667
    29:   8 14.66667 181.66667
    30:   8 15.90000 190.00000
    31:   8 16.10000 228.00000
    32:   8 16.66667 258.00000