【问题标题】:R library(BradleyTerry2). Error in Diff(player1, player2... must be factors with the same levelsR 库(BradleyTerry2)。 Diff中的错误(player1,player2 ...必须是具有相同级别的因素
【发布时间】:2018-11-09 16:06:13
【问题描述】:

我在 R 中使用 BradleyTerry2 包时遇到问题。 我的数据如下所示。我从另一个代码创建数据,我认为格式与 BradleyTerry 示例中的“citations.sf”相同 (https://cran.r-project.org/web/packages/BradleyTerry2/vignettes/BradleyTerry.pdf)

   player1 player2 win1 win2
1        1       2   10    0
2        1       3   10    0
3        1       4    5    5
4        1       5   10    0
5        1       6    9    1
6        2       3    6    4
7        2       4    4    6
8        2       5    5    5
9        2       6    8    2
10       3       4    2    8
11       3       5    7    3
12       3       6    6    4
13       4       5   10    0
14       4       6    9    1
15       5       6    4    6

但是,当我运行speedModel <- BTm(cbind(win1, win2), player1, player2, data = dat) 时,它显示如下错误消息。

Diff 中的错误(player1,player2,formula,id,data,separate.ability,refcat,: 'player1$..' 和 'player2$..' 必须是相同级别的因子

我查看了 StackOverflow 上的另一个页面 (Updated with data: Error in Diff...must be factors with the same levels),并尝试了以下代码。 (不过我不明白它的作用。)

levels(dat[,1]) <- dat(c(dat[,1], dat[,2]))
levels(dat[,2]) <- dat(c(dat[,1], dat[,2]))

但是,BTm() 函数会抛出相同的消息。谁能告诉我我能做什么?

这是dput(dat)的结果

structure(list(player1 = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 
2L, 2L, 2L, 3L, 3L, 3L, 4L, 4L, 5L), .Label = 1:6), player2 = structure(c(2L, 
3L, 4L, 5L, 6L, 3L, 4L, 5L, 6L, 4L, 5L, 6L, 5L, 6L, 6L), .Label = 1:6), 
win1 = c(10L, 10L, 5L, 10L, 9L, 6L, 4L, 5L, 8L, 2L, 7L, 6L, 
10L, 9L, 4L), win2 = c(0L, 0L, 5L, 0L, 1L, 4L, 6L, 5L, 2L, 
8L, 3L, 4L, 0L, 1L, 6L)), row.names = c(NA, -15L), class = "data.frame")

【问题讨论】:

    标签: r bradleyterry2


    【解决方案1】:

    您的问题在于数据框中玩家因素的定义。它们需要具有完全相同的级别,但是因为player1 仅包含值 1、...、5,而 player2 包含值 2、...、6,因此它们将具有不同的级别。

    您需要通过提供确切的水平来强制这两个因素的水平相同。这是通过创建两个具有正确因子水平的新变量来实现此目的的一种方法。

    dat$p1 <- factor(dat$player1, levels=unique(c(dat$player1, dat$player2)))  
    dat$p2 <- factor(dat$player2, levels=unique(c(dat$player1, dat$player2)))  
    

    然后我们就可以运行了

    > speedModel <- BTm(cbind(win1, win2), p1, p2, data = dat)
    > speedModel
    Bradley Terry model fit by glm.fit 
    
    Call:  BTm(outcome = cbind(win1, win2), player1 = p1, player2 = p2, 
        data = indata)
    
    Coefficients:
        ..2      ..3      ..4      ..5      ..6  
    -2.1433  -2.4885  -0.7286  -3.1201  -2.9323  
    
    Degrees of Freedom: 15 Total (i.e. Null);  10 Residual
    Null Deviance:      81.14 
    Residual Deviance: 13.71    AIC: 51.6
    

    【讨论】:

    • 谢谢 ekstroem。这对我来说很有效!我仍然不明白发生了什么,因为 p1 和 p2 在矩阵上看起来与 player1 和 player2 相同。 ...R 很迷人!
    • 您应该阅读 R 因子及其因子水平 - 这就是问题所在
    • 对不起,我不知道这个功能。我刚刚做了,再次感谢你!
    猜你喜欢
    • 2012-07-31
    • 2020-03-16
    • 1970-01-01
    • 2021-12-20
    • 2019-11-21
    • 2014-04-19
    • 2019-05-04
    • 2014-09-08
    • 1970-01-01
    相关资源
    最近更新 更多