2016-08-02 25 views
0

我有一个(x,y)点的表,并且想要创建一个总结这些点的第二个表。如何组合和汇总来自不同大小不同表的R data.table行值?

我希望汇总表中的每一行显示所有y的总和,其中x大于一系列阈值。但是我很难弄清楚如何将行的阈值加入到内部和中。

我到目前为止,这得到:

samples <- data.table(x=seq(1,100,1), y=seq(1,100,1)) 
thresholds = seq(10,100,10) 
thresholdedSums <- data.table(xThreshold=thresholds, ySumWhereXGreaterThanThreshold=sum(samples[x > xThreshold, y])) 

Error in eval(expr, envir, enclos) : object 'xThreshold' not found 

我将如何做到这一点,还是有不同的方式做这样的事情?

为了澄清所需的输出:

thresholdedSums = 
[ 
    (row 1) threshold = 10, ySumWhereXGreaterThanThreshold = sum of all y values in samples[] where x > 10, 
    (row 2) threshold = 20, ySumWhereXGreaterThanThreshold = sum of all y values in samples[] where x > 20, 
    ... etc ... 
] 
+0

'samples [order(-x),。(ytot = sum(y)),by = cut(x,thresholds)] [,res:= cumsum(ytot)] []'?你应该显示所需的输出。你的错误代码很难理解。 – Frank

回答

1

结果可以通过下面的代码进行说明。该解决方案并不完全基于data.table,而是稳健运行。

thresholdedSums <- data.table(
        thres = thresholds, 
        Sum = sapply(thresholds, function(thres) samples[x > thres, sum(y)]) 
        ) 

# thres Sum 
# 1: 10 4995 
# 2: 20 4840 
# 3: 30 4585 
# 4: 40 4230 
# 5: 50 3775 
# 6: 60 3220 
# 7: 70 2565 
# 8: 80 1810 
# 9: 90 955 
# 10: 100 0 

附加说明:sapply(thresholds, function(thres) samples[x > thres, sum(y)])返回相同的长度thresholds的向量。您可以将其读取为:对于thresholds中的每个元素,执行函数function(thres) samples[x > thres, sum(y)]并将结果返回为vector。与for-loop相比,此过程通常性能更好,且易于阅读。

+0

非常好谢谢你,这很好! – DanJ

相关问题