【问题标题】:How do I drop a factor level with no observations? [duplicate]如何在没有观察的情况下降低因子水平? [复制]
【发布时间】:2012-11-22 09:17:00
【问题描述】:

可能重复:
dropping factor levels in a subsetted data frame in R

我有一个包含多个变量的数据框,我正在使用 lme() 运行混合模型。其中一个变量 ForAgeCat 有五个因子水平:1、2、3、4、5。

str(mvthab.3hr.fc$ForAgeCat)
 >Factor w/ 5 levels "1","2","3","4",..: 5 5 5 5 5 5 5 5 5 5 ...

问题是因子级别 3 实际上不存在,也就是说,在这个数据集(它是更大数据集的一个子集)中没有来自因子级别 3 的观察结果,我认为这会影响我的建模lme()。有人可以帮我从因子级别列表中删除/消除因子级别 3 吗?

【问题讨论】:

  • mvthab.3hr.fc$ForAgeCat <- factor(mvthab.3hr.fc$ForAgeCat)

标签: r r-factor


【解决方案1】:

使用函数droplevels,像这样:

> DF$factor_var = droplevels(DF$factor_var)

更多细节:

> # create a sample dataframe:
> col1 = runif(10)
> col1
    [1] 0.6971600 0.1649196 0.5451907 0.9660817 0.8207766 0.9527764 
        0.9643410 0.2179709 0.9302741 0.4195046
> col2 = gl(n=2, k=5, labels=c("M", "F"))
> col2
    [1] M M M M M F F F F F
    Levels: M F
> DF = data.frame(Col1=col1, Col2=col2)
> DF
     Col1 Col2
 1  0.697    M
 2  0.165    M
 3  0.545    M
 4  0.966    M
 5  0.821    M
 6  0.953    F
 7  0.964    F
 8  0.218    F
 9  0.930    F
 10 0.420    F

> # now filter DF so that only *one* factor value remains
> DF1 = DF[DF$Col2=="M",]
> DF1
   Col1 Col2
1 0.697    M
2 0.165    M
3 0.545    M
4 0.966    M
5 0.821    M

> str(DF1)
    'data.frame':   5 obs. of  2 variables:
   $ Col1: num  0.697 0.165 0.545 0.966 0.821
   $ Col2: Factor w/ 2 levels "M","F": 1 1 1 1 1

> # but still 2 factor *levels*, even though only one value

> DF1$Col2 = droplevels(DF1$Col2)
> # now Col2 has only a single level:
> str(DF1)
   'data.frame':    5 obs. of  2 variables:
  $ Col1: num  0.697 0.165 0.545 0.966 0.821
  $ Col2: Factor w/ 1 level "M": 1 1 1 1 1

【讨论】:

  • droplevels 现在是基础R 的一部分。
  • 它还在 gdata 中,但我会根据您的评论编辑我的答案,谢谢。
猜你喜欢
  • 2021-04-17
  • 1970-01-01
  • 1970-01-01
  • 2014-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-29
  • 1970-01-01
相关资源
最近更新 更多