将内存存储库构建到函数中,作为下一个输入输出

时间:2015-07-06 21:49:21

标签: r

我在尝试使用函数的同时构建了一个快速而又脏的elo计算器:

elo <- function(winner, loser, r1, r2){

    player <- c(winner, loser)

    K <- 32 # smoothing constant

    R1 <- 10^(r1/400)
    R2 <- 10^(r2/400)

    E1 <- R1 / (R1 + R2)
    E2 <- R2 / (R1 + R2) 

    S1 <- 1 # Win
    S2 <- 0 # Loss

    rp1 <- r1 + K * (S1 - E1)
    rp2 <- r2 + K * (S2 - E2)

    rating <- c(rp1, rp2)

    data.frame(player, rating)
}

现在我想在能够“记住”每个elo分数的函数中构建一个内存管理(?)/ repository。

现在我用连续的电话手动计算elo:

elo("M1", "A1", 2000, 2000)
elo("M1", "M2", 2016, 2000)
elo("A1", "M2", 1984.736, 1984)
elo("M2", "M1", 2000.7, 2031.264)
elo("M2", "A1", 2018.1, 2000.7)

我希望能够输入赢家和输家(在2000年开始新玩家),并让该功能打印出新结果,同时存储旧值(如果系统时间戳?)

示例:

elo("M1", "A1")

我只是不知道从哪里开始。

任何评论,建设性的批评都表示赞赏。如果这太宽泛,请道歉!

1 个答案:

答案 0 :(得分:0)

我设法保持&#34;得分&#34;通过将.csv文件写入和读取到HDD:

elo <- function(winner, loser){

    setwd("/Users/firstlast/Documents/R/elo/")
    df <- read.csv("df.csv", header = TRUE)

    if (winner %in% df$player){
        df
    } else {
        df <- rbind(df, data.frame(player = winner, rating = 2000))
    }

    if (loser %in% df$player) {
        df 
    } else {
        df <- rbind(df, data.frame(player = loser, rating = 2000))
    }

    K <- 32 # smoothing constant

    r1 <- df[df$player == winner, 2]
    r2 <- df[df$player == loser, 2]

    R1 <- 10^(r1/400)
    R2 <- 10^(r2/400)

    E1 <- R1 / (R1 + R2)
    E2 <- R2 / (R1 + R2) 

    S1 <- 1 # Win
    S2 <- 0 # Loss

    rp1 <- r1 + K * (S1 - E1)
    rp2 <- r2 + K * (S2 - E2)

    df[df$player == winner, 2] <- rp1
    df[df$player == loser, 2] <- rp2

    write.csv(df, "df.csv", row.names = FALSE)
    return(df)
}

我现在如何添加一些历史功能(即随时间跟踪分数)?

必须有更好的方法将新玩家添加到df数据框......我的if else控制结构看起来很可怕!

修改

df的结构如下:

df <- data.frame(
    player = c("M1", "A1"), 
    rating = c(2000, 2000)
)