In R, how to sum certain rows of a data frame with certain logic?

前端 未结 5 1818
情书的邮戳
情书的邮戳 2021-01-06 17:33

Hi experienced R users,

It\'s kind of a simple thing. I want to sum x by Group.1 depending on one controllable variable.

I\'d like

5条回答
  •  情深已故
    2021-01-06 17:58

    Not sure why Eggs are important here ;)

    df1 <- data.frame(Gr=seq(4),
                      x=c(230299, 263066, 266504, 177196)
                      )
    

    now with n=2 i.e. first two rows:

    n <- 2
    sum(df1[, "x"][df1[, "Gr"]<=n]) 
    

    The expression [df1[, "Gr"]<=n] creates a logical vector to subset the elements in df1[, "x"] before summing them.

    Also, it appears your Group.1 is the same as the row no. If so this may be simpler:

    sum(df1[, "x"][1:n])
    

    or to get all at once

    cumsum(df1[, "x"])
    

提交回复
热议问题