Lotus@ 2009-07-28 18:21 采纳率: 100%
浏览 263
已采纳

子集数据帧中的拖放因子级别

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

This creates headaches 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 my new data frame?

Here's my example:

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    

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

转载于:https://stackoverflow.com/questions/1195826/drop-factor-levels-in-a-subsetted-data-frame

  • 写回答

12条回答 默认 最新

  • MAO-EYE 2009-07-28 22:41
    关注

    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
    

    EDIT

    From the factor page example:

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(11条)

报告相同问题?

悬赏问题

  • ¥15 vika文档如何与obsidian同步
  • ¥15 华为手机相册里面的照片能够替换成自己想要的照片吗?
  • ¥15 陆空双模式无人机飞控设置
  • ¥15 sentaurus lithography
  • ¥100 求抖音ck号 或者提ck教程
  • ¥15 关于#linux#的问题:子进程1等待子进程A、B退出后退出(语言-c语言)
  • ¥20 web页面如何打开Outlook 365的全球离线通讯簿功能
  • ¥15 io.jsonwebtoken.security.Keys
  • ¥15 急,ubuntu安装后no caching mode page found等
  • ¥15 联想交换机NE2580O/NE1064TO安装SONIC