4

特定のサッカー選手によるシーズンごとの累積ゴールの統計を作成しようとしています。カット機能を使用して、ゲームの日付からシーズンを取得しました。このデータフレームに対応するデータがあります

df.raw <-
    data.frame(Game = 1:20,
            Goals=c(1,0,0,2,1,0,3,2,0,0,0,1,0,4,1,2,0,0,0,3),     
               season = gl(4,5,labels = c("2001", "2002","2003", "2004")))

実生活では、シーズンごとのゲーム数は一定ではない場合があります

こんな感じのデータで終わりたい

df.seasoned <-
    data.frame(Game = 1:20,seasonGame= rep(1:5),
            Goals=c(1,0,0,2,1,0,3,2,0,0,0,1,0,4,1,2,0,0,0,3),
            cumGoals = c(1,1,1,3,4,0,3,5,5,5,0,1,1,5,6,2,2,2,2,5),     
               season = gl(4,5,labels = c("2001", "2002","2003", "2004")))

年間の累積目標数とシーズンのゲーム数

4

3 に答える 3

6
 df.raw$cumGoals <- with(df.raw,  ave(Goals, season, FUN=cumsum) )
 df.raw$seasonGame <- with(df.raw,  ave(Game, season, FUN=seq))
 df.raw

または transform ... 元の変換、つまり:

df.seas <- transform(df.raw, seasonGame = ave(Game, season, FUN=seq),
                          cumGoals = ave(Goals, season, FUN=cumsum) )
df.seas
   Game Goals season seasonGame cumGoals
1     1     1   2001          1        1
2     2     0   2001          2        1
3     3     0   2001          3        1
4     4     2   2001          4        3
5     5     1   2001          5        4
6     6     0   2002          1        0
7     7     3   2002          2        3
8     8     2   2002          3        5
9     9     0   2002          4        5
10   10     0   2002          5        5
snipped
于 2011-09-13T22:26:33.707 に答える
5

ddplyandの別のジョブtransform(plyrパッケージから):

ddply(df.raw,.(season),transform,seasonGame = 1:NROW(piece),
                                 cumGoals = cumsum(Goals))
   Game Goals season seasonGame cumGoals
1     1     1   2001          1        1
2     2     0   2001          2        1
3     3     0   2001          3        1
4     4     2   2001          4        3
5     5     1   2001          5        4
6     6     0   2002          1        0
7     7     3   2002          2        3
8     8     2   2002          3        5
9     9     0   2002          4        5
10   10     0   2002          5        5
11   11     0   2003          1        0
12   12     1   2003          2        1
13   13     0   2003          3        1
14   14     4   2003          4        5
15   15     1   2003          5        6
16   16     2   2004          1        2
17   17     0   2004          2        2
18   18     0   2004          3        2
19   19     0   2004          4        2
20   20     3   2004          5        5
于 2011-09-13T22:18:47.263 に答える
5

data.tableこれは非常に高速なソリューションです。

library(data.table)
df.raw.tab = data.table(df.raw)
df.raw.tab[,list(seasonGame = 1:NROW(Goals), cumGoals = cumsum(Goals)),'season']
于 2011-09-13T23:48:12.443 に答える