我使用R模拟足球比赛结果,我已经设置了一个循环,每个球队互相对抗。
mod3=glm(formula = Score ~ Attack +Home+Division , family = poisson, data = football)
for (i in 1:20){
for (j in 1:20){
if (i!=j){
teamHome=levels(football$Attack)[i]
teamAway=levels(football$Attack)[j]
teamHome
teamAway
if(i<21){
iteam="P"
} else if(i<45){
iteam="C"
} else if(i<69){
iteam="1"
} else{
iteam="2"
}
if(j<21){
jteam="P"
} else if(j<45){
jteam="C"
} else if(j<69){
jteam="1"
} else{
jteam="2"
}
if(iteam==jteam) {iteam <- "S"; jteam <-"S"}
DivisionS=paste(iteam,jteam," ",sep="")
DivisionJ=paste(jteam,iteam," ",sep="")
homeScore=rpois(1,predict.glm(mod3, data.frame(Attack=teamHome,Home="Y ",Division=DivisionS),type="response"))
awayScore=rpois(1,predict.glm(mod3, data.frame(Attack=teamAway, Home="N ",Division=DivisionJ),type="response"))
Result= if(homeScore>awayScore){
Result="H"
} else if(homeScore<awayScore){
Result="A"
}else if(homeScore==awayScore){
Result="D"
}
results<-print(paste(teamHome,homeScore," ",teamAway,awayScore,DivisionS,DivisionJ,Result),quote=F)
当我运行循环时,我得到的结果如下:
[1] QPR 0 Arsenal 1 SS SS A
[1] QPR 1 Tottenham 1 SS SS D
[1] QPR 2 Everton 1 SS SS H
[1] QPR 1 Liverpool 2 SS SS A
[1] QPR 2 WBA 1 SS SS H
[1] QPR 0 Swansea 2 SS SS A
我需要将结果存储在不同级别,以便我可以使用合适的团队计算H
和A
以及D
的数量,以及团队的目标数量得分或失球。
如何存储打印输出?