R newb。我的數據的小代表。動態計數的發生
TeamHome <- c("LAL", "HOU", "SAS", "LAL")
TeamAway <- c("IND", "SAS", "LAL", "HOU")
df <- data.frame(cbind(TeamHome, TeamAway))
df
TeamHome TeamAway
LAL IND
HOU SAS
SAS LAL
LAL HOU
想象這些成千上萬的遊戲一個賽季的前四場比賽。對於主隊和客隊,我想要計算在家中,在路上和總數上的累計比賽數量。因此,主隊和客隊都有3個新欄目。我想獲得這樣的事情(在這種情況下,我只計算主隊新的變量):
TeamHome TeamAway HomeTeamGamesPlayedatHome HomeTeamGamesPlayedRoad HomeTeamTotalgames
1 LAL IND 1 0 1
2 HOU SAS 1 0 1
3 SAS LAL 1 1 2
4 LAL HOU 2 1 3
要計算第一列(HomeTeamGamesPlayedatHome)我成功做到這一點的:
df$HomeTeamGamesPlayedatHome <- ave(df$TeamHome==df$TeamHome, df$TeamHome, FUN=cumsum)
但感覺過於複雜,我也無法用這種方法計算其他列。
我也想過用公式表計算出現的數量:
table(df$TeamHome)
,但它只是計算總數,我想在任何給定時間點的結果。 謝謝!
好問題,upvote for reproducable example and desired output – user2673238