计算足球队的积分 [英] Computing points for a football team
问题描述
每个人.我正在尝试计算足球队的积分.我有我的数据框df.work"行名=团队名: rownames(df.work)<-c(as.vector(teams $ HomeTeam))
everyone.
I am trying to calculate football team points.
I have my dataframe "df.work" with rownames = teamnames:
rownames(df.work) <- c(as.vector(teams$HomeTeam))
我已从另一个数据帧导入了所有已进行的比赛.对于每个团队,我都尝试根据团队匹配项的子集执行if循环.首先,我过滤所有主场比赛.所以我的代码是
I have imported all played matches from another dataframe. And for every team I try to execute if loop based on subset of team matches. First I filter all home matches. So my code is
for (Team1 in row.names.data.frame(df.work)){
a1 <- filter(df.clean, HomeTeam == Team1)
if (a1$home.goals > a1$away.goals) {
df.work[Team1,"Points"] <- df.work[Team1,"Points"] + 3
} else if(a1$home.goals == a1$away.goals) {
df.work[Team1,"Points"] <- df.work[Team1,"Points"] + 1
}
但是我很努力,为什么它没有对a1中的每一行进行循环并求和呢?
But I struggle why it did not loop for every row in a1 and sum the points?
这是头(df.clean):
this is head(df.clean):
HomeTeam AwayTeam home.goals away.goals
1 Liverpool Norwich 4 1
2 West Ham Man City 0 5
3 Bournemouth Sheffield United 1 1
4 Burnley Southampton 3 0
5 Crystal Palace Everton 0 0
6 Watford Brighton 0 3
头(df.work)是
and head(df.work) is
Games Goals.Scored Goals.Conceded Points
Liverpool 32 70 25 3
West Ham 32 38 56 0
Bournemouth 32 30 54 1
Burnley 32 36 45 3
Crystal Palace 32 28 37 1
Watford 32 29 49 0
推荐答案
我相信以下是问题的要求.
I believe the following is what the question asks for.
goals2points <- function(x, y){
pnts <- sign(x - y) + 1
pnts[pnts == 2] <- 3
sum(pnts)
}
hg <- aggregate(home.goals ~ HomeTeam, df.clean, sum)
ag <- aggregate(away.goals ~ AwayTeam, df.clean, sum)
Goals.Scored <- hg[[2]] + ag[[2]]
hg <- aggregate(home.goals ~ AwayTeam, df.clean, sum)
ag <- aggregate(away.goals ~ HomeTeam, df.clean, sum)
Goals.Conceded <- hg[[2]] + ag[[2]]
sp1 <- split(df.clean, df.clean$HomeTeam)
home <- sapply(sp1, function(DF){
goals2points(DF[['home.goals']], DF[['away.goals']])
})
sp2 <- split(df.clean, df.clean$AwayTeam)
away <- sapply(sp2, function(DF){
goals2points(DF[['away.goals']], DF[['home.goals']])
})
Points <- rowSums(cbind(home, away))
result <- data.frame(Games = lengths(sp1) + lengths(sp2),
Goals.Scored,
Goals.Conceded,
Points)
result
# Games Goals.Scored Goals.Conceded Points
#A 8 24 22 12
#B 8 26 21 15
#C 8 23 21 12
#D 8 17 24 7
#E 8 23 25 13
测试数据
set.seed(2020)
df.clean <- expand.grid(HomeTeam = LETTERS[1:5], AwayTeam = LETTERS[1:5])
df.clean <- df.clean[apply(df.clean, 1, function(x) x[1] != x[2]), ]
df.clean$home.goals <- sample(0:5, nrow(df.clean), TRUE)
df.clean$away.goals <- sample(0:5, nrow(df.clean), TRUE)
这篇关于计算足球队的积分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!