首页 > 解决方案 > 在 R 中创建一个 excel 单向数据表——我的 for 循环有问题

问题描述

我正在尝试在 R 中创建一个 excel 单向数据表,以便我可以找到最小化方程中系数误差的指数。我有一个产生正确结果的 for 循环,但它做了一些我无法弄清楚的奇怪事情。

这是数据的示例。我将使用棒球中的毕达哥拉斯获胜公式,并使用 for 循环来找到使获胜预测中的平均绝对误差最小化的指数。

## Create Data

Teams <- c("Bulls", "Sharks", "Snakes", "Dogs", "Cats")
Wins <- c(5, 3, 8, 1, 9)
Losses <- 10 - Wins
Win.Pct <- Wins/(Wins + Losses)
Points.Gained <- c(30, 50, 44, 28, 60)
Points.Allowed <- c(28, 74, 40, 92, 25)
season <- data.frame(Teams, Wins, Losses, Win.Pct, Points.Gained, Points.Allowed)
season

## Calculate Scoring Ratio

season$Score.Ratio <- with(season, Points.Gained/Points.Allowed)

## Predict Wins from Scoring Ratio

exponent <- 2

season$Predicted.Wins <- season$Score.Ratio^exponent / (1 + season$Score.Ratio^exponent)

## Calculate Mean Absolute Error

season$Abs.Error <- with(season, abs(Win.Pct - Predicted.Wins))

mae <- mean(season$Abs.Error)
mae

这是我的 for 循环,它正在查看一系列指数选项,以查看它们是否比上面使用的指数 2 更好。出于某种奇怪的原因,当我运行 for 循环时,它会不断重复该表数次(许多表的结果不正确),直到最终生成正确的表作为最后一个表。谁能向我解释我的 for 循环有什么问题以及为什么会这样?

## Identify potential exponent options that minimize mean absolute error

exp.options <- seq(from = 0.5, to = 3, by = 0.1)
mae.results <- data.frame("Exp" = exp.options, "Results" = NA)

for(i in 1:length(exp.options)){
    win.pct <- season$Predicted.Wins
    pred.win.pct <- 
        (season$Points.Gained/season$Points.Allowed)^exp.options[i] / 
        (1 + (season$Points.Gained/season$Points.Allowed)^exp.options[i])

    mae.results[i,2] <- mean(abs(win.pct - pred.win.pct))
    print(mae.results) 
    }

标签: rfor-loop

解决方案


推荐阅读