簡體   English   中英

如何合並和匯總來自不同大小的不同表的R data.table行值?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM