gpt4 book ai didi

r - 结合 split() 和 cumsum()

转载 作者:行者123 更新时间:2023-12-04 12:17:40 26 4
gpt4 key购买 nike

我正在尝试生成特定足球运动员按赛季累积目标的统计数据。我使用 cut 函数从游戏日期中获取季节。我有与此数据框对应的数据

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")))

年内累计进球数和本赛季的比赛次数

最佳答案

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

或使用变换...原始变换,即:
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

关于r - 结合 split() 和 cumsum(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7409138/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com