You can use rollapply
, or sapply
/outer
, to get a matrix of indices and then apply
over that matrix with the operation you want
inds <- rollapply(seq_len(nrow(dt)), width = 10, FUN = I)
# or inds <- t(sapply(seq_len(1 + nrow(dt) - 10) - 1, `+`, 1:10))
# or inds <- outer(seq_len(1 + nrow(dt) - 10) - 1, 1:10, `+`)
# or inds <- embed(1:100, 10)[, 10:1] # thanks @Frank
apply(inds, 1, function(i) dt[i, mean(x == y)])
# [1] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
# [20] 0.0 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.2 0.2 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1
# [39] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.1 0.1 0.1 0.1 0.1
# [58] 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.0 0.0 0.0 0.0
# [77] 0.1 0.1 0.1 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.1 0.1 0.1 0.0 0.0
Although if the operation is as simple as this example you can also do
dt[, rollapply(x == y, width = 10, FUN = mean)]