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

后端 未结 2 1576
佛祖请我去吃肉
佛祖请我去吃肉 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:30

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题