在R语言中按球队分组计算加权滚动平均值的方案求助
在R中按球队分组批量计算加权滚动平均值
我有一个名为games_h的DataFrame,仅展示了部分数据,实际包含多支球队信息,且已按日期、球队、比赛编号排序。希望按Team字段分组,对指定列计算加权滚动平均值——规则是最近一场比赛权重高于前一场(比如权重比2:1,计算公式为(Game_1*1 + Game_2*2)/3)。
数据结构
games_h的结构如下:
dput(games_h) structure(list(GameId = c(16, 16, 37, 37, 57, 57), GameDate = structure(c(17905, 17905, 17916, 17916, 17926, 17926), class = "Date"), NeutralSite = c(0, 0, 0, 0, 0, 0), AwayTeam = c("Virginia Cavaliers", "Virginia Cavaliers", "Florida State Seminoles", "Florida State Seminoles", "Syracuse Orange", "Syracuse Orange"), HomeTeam = c("Boston College Eagles", "Boston College Eagles", "Boston College Eagles", "Boston College Eagles", "Boston College Eagles", "Boston College Eagles"), Team = c("Virginia Cavaliers", "Boston College Eagles", "Florida State Seminoles", "Boston College Eagles", "Syracuse Orange", "Boston College Eagles"), Home = c(0, 1, 0, 1, 0, 1), Score = c(83, 56, 82, 87, 77, 71), AST = c(17, 6, 12, 16, 11, 13), TOV = c(10, 8, 9, 13, 11, 11), STL = c(5, 4, 4, 6, 6, 5), BLK = c(6, 0, 4, 4, 1, 0), Rebounds = c(38, 18, 36, 33, 23, 23), ORB = c(7, 4, 16, 10, 7, 6), DRB = c(31, 14, 20, 23, 16, 17), FGA = c(55, 57, 67, 55, 52, 45), FGM = c(33, 22, 28, 27, 29, 21), X3FGM = c(8, 7, 8, 13, 11, 9), X3FGA = c(19, 25, 25, 21, 26, 22), FTA = c(14, 9, 24, 28, 15, 23), FTM = c(9, 5, 18, 20, 8, 20), Fouls = c(16, 12, 25, 20, 19, 19), Game_Number = 1:6, Count = c(1, 1, 1, 1, 1, 1)), class = c("grouped_df", "tbl_df", "tbl", "data.frame" ), row.names = c(NA, -6L), groups = structure(list(HomeTeam = "Boston College Eagles", .rows = structure(list(1:6), ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame" ), row.names = c(NA, -1L), .drop = TRUE))
预期输出
以Score列为例,预期输出如下:
尝试代码
我自己编写了加权平均计算函数,但无法批量应用到分组后的指定列中,尝试的代码如下:
weighted_avg<-function(x, wt1, wt2) { rs1 = rollsum(x,1,align = "right") rs2 = rollsum(x,2,align = "right") rs1=rs1[-1] rs3 = rs2 - rs1 weighted_avg= ((rs3 * wt2)+ (rs1*wt1))/(wt1+wt2) return(weighted_avg) } weighted_avg(csum$Score_Y, 2, 1) apply(csum$Score_Y , 2, weighted_avg, wt1 = 2, wt2=1) test<-csum %>% group_by(Team)%>% group_map(across(c(Score:Fouls), weighted_avg(.x$Team, 2, 1) )) test<-csum %>% group_by(Team)%>% group_walk(across(c(Score:Fouls),weighted_avg(.~,2,1) ))
需求
请给出解决方案:如何在R中按Team分组,将上述加权平均函数批量应用到Score至Fouls的列中。
内容的提问来源于stack exchange,提问作者d3hero23
相关产品推荐
相关产品推荐

