删除子集数据框中未使用的因子水平

删除子集数据框中未使用的因子水平

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

问题描述

我有一个包含 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)

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

08-06 05:20