Sliding window calculation using R
Your code is inefficient because each iteration within the sapply has to search through the 100k rows of data to find the relevant ones. Without changing your code at all, you could get a significant speed improvement by first pre-aggregating your input data:

dat &lt;- aggregate(lab ~ index, data = dat, FUN = sum)


This way, each iteration will only have to search through $M = 2154$ rows instead of the 100k. But it is not fixing everything and I prefer rewriting your code with your more general goal in mind, where

indx.vec &lt;- c(1:10, 14:20)


First, aggregate your data using tapply:

agg.lab &lt;- with(dat, tapply(lab, list(index), FUN = sum))
length(agg.lab)
# [1] 2154
head(agg.lab)
#  1  2  3  4  5  6 
# 25 23 26 21 22 21


It returns a vector containing sum(lab) for each distinct value of index. In the event that the data has no value for a given index, you could overwrite the output-ed NA with a 0 so as to not affect the upcoming roll sums:

agg.lab[is.na(agg.lab)] &lt;- 0


Next, we subset by only keeping the indices in indx.vec

agg.lab   &lt;- agg.lab[indx.vec]
#  1  2  3  4  5  6  7  8  9 10 14 15 16 17 18 19 20 
# 25 23 26 21 22 21 19 21 24 28 21 18 24 22 23 21 20 


Next, we map each value of indx.vec to the "group number" it belongs to (here, 1:14 belong to group #1 then 14:20 belong to group #2):

indx.grp  &lt;- cumsum(c(TRUE, diff(indx.vec) != 1))
# [1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2


Using this vector of group indices, we break agg.lab into a list of vectors, one for each group number:

agg.split &lt;- split(agg.lab, indx.grp)
# $`1`
#  1  2  3  4  5  6  7  8  9 10 
# 25 23 26 21 22 21 19 21 24 28 
# 
# $`2`
# 14 15 16 17 18 19 20 
# 21 18 24 22 23 21 20 


Finally, we rollsum within each vector (where I used width = 4 for illustration)

out &lt;- lapply(agg.split, zoo::rollsum, k = width)
# $`1`
#  2  3  4  5  6  7  8 
# 95 92 90 83 83 85 92 
# 
# $`2`
# 15 16 17 18 
# 85 87 90 86


With indx.vec &lt;- 1:M, this code runs in 0.015 seconds on my machine, versus 12+ seconds for your count.ones. It also scales pretty well as it 
takes less than 0.4 sec for n1 = n2 = 1e6.