基于指定值的累积总和

时间:2014-06-20 22:43:56

标签: r

我有一个包含一列(深度,z)的数据框,其中我试图根据常规深度值找出累积深度值的差异。我想创建一个包含2列的新数据框:条件值及其各自的累积深度值,例如:

z<-as.data.frame(c(1:20)) #Original depth values. 
crit<-c(5,10,15,20)       #Criteria for choosing cumulative z-values
crit.d<-as.data.frame(crit) #New dataframe to which respective cumulative values should be added
sum(subset(z, c(1:20) <= 5)) # This will give me the first cumulative value that I need. 

但是我想获得crit = 10,15和20的值。理想情况下,新数据框看起来像

crit     cumulative
 5          15
 10         55
 15         120
 20         210

注意:这是我数据的简化表示,计算每个第x个位置的累计z值都不起作用。我的数据集的反射样本将是

z1<-c(1.2, 1.5, 0.8, 0.7, 1.6, 1.9, 1.1, 0.6, 1.3, 1.0)
z1<-data.frame(z1)
crit1<-c(0.5,1,1.5,2)

# A loop comes to mind, 

for(i in c(0.5,1,1.5,2)){
print( sum(subset(z1,z1<=i)))
}                               # But I get an error, because I cannot use integers

Error in FUN(X[[1L]], ...) : 
only defined on a data frame with all numeric variables

尝试使用cumsum

 cumsum(z1)[seq(0.5,2,by=0.5)] # Which doesn't work either

1 个答案:

答案 0 :(得分:1)

merge为您做到这一点。

z <- as.data.frame(c(1:20))

merge(crit.d,
      data.frame(crit=z[[1]], cumulative=cumsum(z[[1]]))
)
  crit cumulative
1    5         15
2   10         55
3   15        120
4   20        210