2014-12-04 58 views
1

我有一個DF看起來像這樣一個數據幀:子集基於列的總和

> 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 

我想使用列value,即總和子集的話,我想提取的行來自列value的值的總和高於0.6,但是從第一行開始求和值。我期望的結果應該是:

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

我已經試過df2[, colSums[,5]>=0.6]但顯然colSums期待一個array

在此先感謝

回答

1

以下是一種方法:

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

結果:

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

我不知道我的理解正是你正在嘗試這樣做,但我認爲cumsum應該能夠提供幫助。

首先使這種重複性,我們使用dput以便其他人可以幫助:

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)) 

然後看看什麼cumsum(df$value)規定:

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

最後,子集,因此:

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 
+0

謝謝,我忘了cumsum – user2380782 2014-12-04 14:15:14