user2380782
user2380782

Reputation: 1446

subset a dataframe based on sum of a column

I have a df that looks like this:

> df2
  name      value
1    a 0.20019421
2    b 0.17996454
3    c 0.14257010
4    d 0.14257010 
5    e 0.11258865
6    f 0.07228970
7    g 0.05673759
8    h 0.05319149
9    i 0.03989362

I would like to subset it using the sum of the column value, i.e, I want to extract those rows which sum of values from column value is higher than 0.6, but starting to sum values from the first row. My desired output will be:

> df2
  name      value
1    a 0.20019421
2    b 0.17996454
3    c 0.14257010
4    d 0.14257010

I have tried df2[, colSums[,5]>=0.6] but obviously colSums is expecting an array

Thanks in advance

Upvotes: 1

Views: 1732

Answers (2)

Sven Hohenstein
Sven Hohenstein

Reputation: 81693

Here's an approach:

 df2[seq(which(cumsum(df2$value) >= 0.6)[1]), ]

The result:

  name     value
1    a 0.2001942
2    b 0.1799645
3    c 0.1425701
4    d 0.1425701

Upvotes: 2

JasonAizkalns
JasonAizkalns

Reputation: 20463

I'm not sure I understand exactly what you are trying to do, but I think cumsum should be able to help.

First to make this reproducible, let's use dput so others can help:

df <- structure(list(name = structure(1:9, .Label = c("a", "b", "c", 
"d", "e", "f", "g", "h", "i"), class = "factor"), value = c(0.20019421, 
0.17996454, 0.1425701, 0.1425701, 0.11258865, 0.0722897, 0.05673759, 
0.05319149, 0.03989362)), .Names = c("name", "value"), class = "data.frame", row.names = c(NA, 
-9L))

Then look at what cumsum(df$value) provides:

cumsum(df$value)
# [1] 0.2001942 0.3801587 0.5227289 0.6652990 0.7778876 0.8501773 0.9069149 0.9601064 1.0000000

Finally, subset accordingly:

subset(df, cumsum(df$value) <= 0.6)
#   name     value
# 1    a 0.2001942
# 2    b 0.1799645
# 3    c 0.1425701

subset(df, cumsum(df$value) >= 0.6)
#   name      value
# 4    d 0.14257010
# 5    e 0.11258865
# 6    f 0.07228970
# 7    g 0.05673759
# 8    h 0.05319149
# 9    i 0.03989362

Upvotes: 2

Related Questions