r - 将因子重新调整为默认顺序时出现问题吗?

标签 r factors levels

我有这个df

df = data.frame(x = 1:3)

转换为因子

df$x = factor(df$x)

默认级别为

str(df)

现在让我们将级别 2 作为引用级别

df$x = relevel(df$x,ref=2)

到目前为止一切都还好。但当决定再次将级别 1 作为默认级别时,它不起作用

df$x = relevel(df$x,ref=2)

str(df)


df$x = relevel(df$x,ref=1)

str(df)

感谢帮助。

最佳答案

来自?重新级别

     ref: the reference level, typically a string.

我将取消“通常”。看一下stats:::relevel.factor的代码,一个关键部分是

    if (is.character(ref)) 
        ref <- match(ref, lev)

这对我来说意味着,在这个表达式之后,ref现在(假设是)一个integer,对应于索引内水平。在这种情况下,您的 ref=1 表示按其索引使用第一个级别(它已经是第一个)。

尝试使用字符串。

relevel(df$x,ref=1)
# [1] 1 2 3
# Levels: 2 1 3
relevel(df$x,ref="1")
# [1] 1 2 3
# Levels: 1 2 3

关于r - 将因子重新调整为默认顺序时出现问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74492068/

相关文章:

c - 分解循环的结束条件

android - 放大和缩小的 ImageView 问题,以最大和最小级别拖动

arrays - 访问数组的元素和因子

c++ - 一个数的最大除数与质因数的关系

r - 在 R 中使用 mlogit 的级别错误

r - 具有自定义截止值的 pROC R 包?

r - 在 R 中按特定顺序对数据进行排序

r - R中的静态变量

r - 如何根据其他列的值在 data.table 中创建新列