/ /複数の条件での頻度カウントR-r、count、data.table、frequency

複数の条件を持つ頻度カウント

データフレームを持っている

Date         Team            Opponent   Weather   Outcome
2017-05-01   All Stars       B Stars      Rainy     1
2017-05-02   All Stars       V Stars      Rainy     1
2017-05-03   All Stars       M Trade      Sunny     0
.
.
2017-05-11   All Stars       Vdronee      Sunny     0

結果1は勝利を示します。テーブル関数を使用して、頻度と適用条件を取得しました。

table(df$Outcome, df$Team == "All Stars")

私にこれを返します

    FALSE TRUE
0  1005   30
1  1323   57

したがって、勝ちの頻度は57/87 = 0.655です。

2つの質問:

勝率を手動で計算するのではなく、これを数式に直接埋め込むにはどうすればよいですか?

そして

x個の最新の観測値に基づいてフィルタリングするにはどうすればよいですか?つまり、

    table(df$Outcome, df$Team == "All Stars" & df$date = filtering for the 5 most recent observations)

ありがとう

回答:

回答№1は0

オプションは使用することです data.table

libray(data.table)
dt <- data.table(df)
dt[, .(prop=sum(outcome)/.N),Team]

最新の5つの観測値を取得するには、次のようにします。

dt[,head(.SD,5),by=.(Team,Date)][,.(prop=sum(outcoume/.N),Team]