Home > Blockchain >  Apply frollapply only on specific rows in data table
Apply frollapply only on specific rows in data table

Time:02-16

Lets say I have simple DT:

library(data.table)


DT <- data.table(x = 1:20)

I want to apply frollapply function on specific rows of the DT. For exmaple this code applies function on every row:

DT[, frollapply(x, n = 10, FUN = function(y) sum(y, na.rm = TRUE))]

but I want to return only 11 and 13, that is, numbers 65 and 85.

I know I can subset AFTER I applied frollapply, but than I will execute the function on every row.

Something like this doesn't work (it seems it first subset and than apply):

DT[c(11, 13), frollapply(x, n = 10, FUN = function(y) sum(y, na.rm = TRUE))]

CodePudding user response:

The point of the rolling functions (apply/sum/mean) is precisely to apply the function on the whole vector. If you just need 2 values, the easiest way is just to ask for only those values:

DT[, sapply(c(11, 13), function(i) sum(x[(i-9):i]))]
#[1] 65 85

CodePudding user response:

You cannot directly subset 11-13 as you need your previous values to calculate the rolling sum, but you do not need the values after 13, so you can subset first on 1:13 and only calculate the rolling sum for those. Then subset again for 11:13.

DT[c(1:13), frollapply(x, n = 10, FUN = function(y) sum(y, na.rm = TRUE))][c(11, 13)]

# [1] 65 85
  • Related