This comes as an application to this question:Sum object in a column between an interval defined by another column
What I would like to know is how to adjust the answer
I would create a for loop that tests whether A[i] - A[i-1] meets your criteria.
If that is true it adds b[i] to a sum variable and repeats its way through.
Because i is just iterating through A[] it shouldn't count anything from B[] twice.
Try the following, assuming your original dataframe is df
:
df2 <- df # create a duplicate df to destroy
z <- data.frame(nrow=length(unique(df$A)), ncol=2) # output dataframe
names(z) <- c("A","B")
j <- 1 # output indexing variable
u <- unique(df$A) # unique vals of A
i <- u[1]
s <- TRUE # just for the while() loop
while(s){
z[j,] <- c(i,sum(df2[df2$A %in% c(i-1,i,i+1),2]))
df2 <- df2[!df2$A %in% c(i-1,i,i+1),]
j <- j + 1 # index the output
u <- u[!u %in% c(i-1,i,i+1)] # cleanup the u vector
if(length(u)==0) # conditionally exit the loop
s <- FALSE
else
i <- min(u) # reset value to sum by
}
I know that's kind of messy code, but it's a sort of tough problem given all of the different indices.