运行下面的代码时出现错误:
data[, 4] 中的错误:维数不正确
data [,4]和目标的长度相同(480),所以我不明白问题出在哪里。数据是一个有 4 列的 data.frame,目标是一个长度为 480 的向量。
library(glmmTMB)
simulate_games = function(data) {
mod <- glmmTMB(goals ~ home + (1|attack) + (1|defence), poisson, data=data, REML=TRUE)
goals = predict(mod,newdata = data, type = "response")
data[,4] = goals #Error here
res = comp_ranks(goals)[,2] #comp_ranks is a user defined function
for (i in 1:1000) {
data[,4] = rpois(480,goals)
res = cbind(res,comp_ranks(data)[,2])
}
return(res)
}
long <- read.csv("https://www.math.ntnu.no/emner/TMA4315/2020h/eliteserie.csv", colClasses = c("factor","factor","factor","numeric"))
simulate_games(long)
这也是comp_ranks函数,尽管我认为它不是导致错误的原因。
comp_ranks = function(data) {
goals = data[,4]
goals = goals[!is.na(goals)]
teams = unique(data[,1])
teams_points = cbind.data.frame(0,teams)
goals_scored = cbind.data.frame(0,teams)
goals_conceded = cbind.data.frame(0,teams)
for (i in 1:length(teams)) {
tfs = data[,1] == teams[i]
tfc = data[,2] == teams[i]
goals_scored[i,1] = sum(na.omit(goals[tfs]))
goals_conceded[i,1] = sum(na.omit(goals[tfc]))
}
for (i in seq(1,length(goals)-1,2)) {
idx_1 = match(data[,1][i],teams)
idx_2 = match(data[,1][i+1],teams)
if (goals[i] - goals[i+1] > 0) {
teams_points[idx_1,1] = teams_points[idx_1,1] + 3
}
else if (goals[i] - goals[i+1] < 0 ) {
teams_points[idx_2,1] = teams_points[idx_2,1] + 3
}
else {
teams_points[idx_1,1] = teams_points[idx_1,1] + 1
teams_points[idx_2,1] = teams_points[idx_2,1] + 1
}
}
#Sort data.frame by ranks
colnames(teams_points) = c("Points","Teams")
teams_points = teams_points[with(teams_points, order(-Points)), ]
diff = goals_scored[,1] - goals_conceded[,1]
goals_diff = cbind.data.frame(diff,teams)
teams_ranked = teams_points[,2]
for (i in 1:length(teams_points)) {
for (j in 1:length(teams_points)) {
if(j != i) {
if (teams_points[i,1] == teams_points[j,1]) {
if (goals_diff[i,1] == goals_diff[j,1]) {
if (goals_scored[i,1] < goals_scored[j,1] ) {
teams_ranked = replace(teams_ranked,c(i,j), teams_ranked[c(j,i)])
teams_points[,2] = teams_ranked
}
else if(goals_diff[i,1] < goals_diff[j,1] ) {
teams_ranked = replace(teams_ranked,c(i,j), teams_ranked[c(j,i)])
teams_points[,2] = teams_ranked
}
}
}
}
}
}
ranks = data.frame("Ranks" = c(1:16), "Teams" = teams_points[,2], "Points" = teams_points[,1])
return(ranks)
}