本文介绍了在子数据框中删除未使用的因子水平的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含factor的数据框.当我使用subset或其他索引功能创建此数据框的子集时,将创建一个新的数据框.但是,factor变量会保留其所有原始级别,即使/如果新数据帧中不存在它们,也是如此.

I have a data frame containing a factor. When I create a subset of this dataframe using subset or another indexing function, a new data frame is created. However, the factor variable retains all of its original levels, even when/if they do not exist in the new dataframe.

这在进行多面图绘制或使用依赖于因子水平的函数时会引起问题.

This causes problems when doing faceted plotting or using functions that rely on factor levels.

从新数据框中的因素中删除级别的最简洁方法是什么?

What is the most succinct way to remove levels from a factor in the new dataframe?

这是一个例子:

df <- data.frame(letters=letters[1:5],
                    numbers=seq(1:5))

levels(df$letters)
## [1] "a" "b" "c" "d" "e"

subdf <- subset(df, numbers <= 3)
##   letters numbers
## 1       a       1
## 2       b       2
## 3       c       3    

# all levels are still there!
levels(subdf$letters)
## [1] "a" "b" "c" "d" "e"

推荐答案

所有您需要做的就是在子集设置之后再次将factor()应用于变量:

All you should have to do is to apply factor() to your variable again after subsetting:

> subdf$letters
[1] a b c
Levels: a b c d e
subdf$letters <- factor(subdf$letters)
> subdf$letters
[1] a b c
Levels: a b c

编辑

从因子页面示例中:

factor(ff)      # drops the levels that do not occur

要从数据框中的所有因子列中删除级别,可以使用:

For dropping levels from all factor columns in a dataframe, you can use:

subdf <- subset(df, numbers <= 3)
subdf[] <- lapply(subdf, function(x) if(is.factor(x)) factor(x) else x)

这篇关于在子数据框中删除未使用的因子水平的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 10:41