[英]R data.table Conditional Sum: Cleaner way
當然,這是一個非常經常遇到的問題,因此我在此處就此已經想到了許多問題。 但是,我能找到的所有答案都非常具體地針對該問題,並且經常遇到變通方法(您不必這樣做,在這種情況下, foobar更好)或非data.table解決方案。 也許這是因為它應該對data.table毫無疑問
我有一個data.table,其中包含tentgelt
和te_med
年度數據。 對於每一年,我想知道tentgelt > te_med
的觀測份額。 這就是我在做什么:
# note that nAbove and nBelow do not add up to 1
nAbove <- wages[tentgelt > te_med, list(nAbove = .N), by=list(year)]
nBelow <- wages[tentgelt < te_med, list(nBelow = .N), by=list(year)]
nBelow[nAbove][, list(year, foo=nAbove/(nAbove+nBelow))]
可以,但是每當我看到其他人的data.table
代碼時,它都比我的解決方法更清晰,更容易。 有沒有更干凈的方法來獲取以下類型的輸出?
year foo
1: 1993 0.2372093
2: 1994 0.1567568
3: 1995 0.8132530
4: 1996 0.1235955
5: 1997 0.1065574
6: 1998 0.3070684
7: 1999 0.1491974
這是我的數據示例:
year tentgelt te_med
1: 2010 120.95 53.64929
2: 2010 9.99 116.72601
3: 2010 113.52 53.07394
4: 2010 10.27 38.45728
5: 2010 48.58 124.65753
6: 2010 96.38 86.99060
7: 2010 3.46 65.75342
8: 2010 107.52 91.87592
9: 2010 107.52 42.92953
10: 2010 3.46 73.92328
11: 2010 96.38 85.23419
12: 2010 2.25 79.19995
13: 2010 42.32 35.75757
14: 2010 7.94 93.44305
15: 2010 120.95 113.41370
16: 2010 7.94 110.68628
17: 2010 107.52 127.30682
18: 2010 2.25 103.49036
19: 2010 120.95 123.62054
20: 2010 96.38 68.57532
對於此樣本, 預期輸出應為:
year V2
1: 2010 0.45
嘗試這個
wages[, list(foo= sum(tentgelt > te_med)/.N), by = year]
# year foo
# 1: 2010 0.45
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.