R - How to sum objects in a column between an interval defined by conditions on another column

后端 未结 2 1581
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-28 10:04

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

2条回答
  •  广开言路
    2021-01-28 10:42

    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.

提交回复
热议问题