[英]How to combine and summarize R data.table rows values from different tables of different sizes?
我有一个(x,y)点的表,想创建第二个表来总结这些点。
我希望摘要表中的每一行都显示x大于阈值序列的所有y的总和。 但是我很难弄清楚如何将行的阈值加入内部和。
我已经走了这么远:
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 ...
]
结果可以通过以下代码给出。 此解决方案并不完全基于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
相比,此过程通常在性能上更好并且更易于阅读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.