R - 将因子的参考水平设置为NA

时间:2015-02-05 15:45:53

标签: r r-factor categorical-data

我有一个带有因子列的data.table,其中一些值是NA。我故意将NA作为因子的一个级别(即x <- factor(x, exclude=NULL),而不是x <- factor(x, exclude=NA)的默认行为),因为NA对我的模型有意义。对于这些因子列,我希望relevel()参考级别为NA,但我正在努力学习语法。

# silly reproducible example
library(data.table)
a <- data.table(animal = c("turkey","platypus","dolphin"),
            mass_kg = c(8, 2, 200),
            egg_size= c("large","small",NA),
            intelligent=c(0,0,1)
            )
lr <- glm(intelligent ~ mass_kg + egg_size, data=a, family = binomial)
summary(lr) 

# By default, egg_size is converted to a factor with no level for NA
# However, in this case NA is meaningful (since most mammals don't lay eggs)

a[,egg_size:=factor(egg_size, exclude=NULL) ] # exclude=NULL allows an NA level

lr <- glm(intelligent ~ mass_kg + egg_size, data=a, family = binomial)
summary(lr) # Now NA is included in the model, but not as the reference level

a[,levels(egg_size)] # Returns: [1] "large" "small" NA    

a[,egg_size:=relevel(egg_size,ref=NA)]
# Returns:
# Error in relevel.factor(egg_size, ref = NA) : 
#   'ref' must be an existing level

relevel()的正确语法是什么,还是需要使用其他内容?非常感谢。

1 个答案:

答案 0 :(得分:1)

您必须指定正确的NA类型,即NA_character_,但然后会抛出NA,这可能是一个错误。解决方法是直接指定级别:

# throw out NA's to begin with
egg_size = factor(c("large","small",NA), exclude = NA)

# but then add them back at the beginning
factor(egg_size, c(NA, levels(egg_size)), exclude = NULL)
#[1] large small <NA> 
#Levels: <NA> large small

如果您想知道,cNAlogical转换为正确的类型。