【问题标题】:Difference in cumulative sum based on specified values基于指定值的累积和差异
【发布时间】:2014-06-21 14:36:51
【问题描述】:

我有一个包含一列 (depth, z) 的数据框,我试图在其中找到基于常规深度值的累积深度值的差异。我想创建一个包含 3 列的新数据框:标准值、其各自的累积深度值以及具有连续累积深度之间差异的第三列,例如:

z1<-c(1.2, 1.5, 0.8, 0.7, 1.6, 1.9, 1.1, 0.6, 1.3, 1.0)
z<-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

我想要一张这样的桌子:

Crit     Cumulative      Difference
  0.5        0                0
  1          3.1              3.1
  1.5        8.2              5.1

【问题讨论】:

  • 感谢您的指出。

标签: r


【解决方案1】:

不要在这里使用for循环,你应该使用sapply,因为你存储了结果。

y <- sapply(crit1,function(x)sum(z1[z1<=x]))
d <- c(0,diff(y))

data.frame(Crit =  crit1,  Cumulative  =y,    Difference=d)

#   Crit Cumulative Difference
# 1  0.5        0.0        0.0
# 2  1.0        3.1        3.1
# 3  1.5        8.2        5.1
# 4  2.0       11.7        3.5

【讨论】:

    【解决方案2】:

    你可以试试

     Difference <- setNames(c(0,tapply(z1,cut(z1, breaks=crit1,labels=F),FUN=sum)),NULL)
     data.frame(Crit=crit1, Cumulative=cumsum(Difference), Difference)
    #    Crit Cumulative Difference
    #1  0.5        0.0        0.0
    #2  1.0        3.1        3.1
    #3  1.5        8.2        5.1
    #4  2.0       11.7        3.5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-11
      • 2018-04-09
      • 2022-10-02
      • 2021-01-04
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      相关资源
      最近更新 更多