【问题标题】:Updating factor levels while filtering R data.frames [duplicate]在过滤R data.frames时更新因子水平[重复]
【发布时间】:2013-12-28 06:33:54
【问题描述】:

我有一个类似于下面的 data.frame。我通过删除我不感兴趣的行来对其进行预处理。我的大多数列都是“因素”,当我过滤 data.frame 时,它​​们的“级别”不会更新。

我可以看到我在下面做的并不理想。如何在修改 data.frame 时更新因子水平?以下是问题所在的演示。

# generate data
set.seed(2013)
df <- data.frame(site = sample(c("A","B","C"), 50, replace = TRUE),
                 currency = sample(c("USD", "EUR", "GBP", "CNY", "CHF"),50, replace=TRUE, prob=c(10,6,5,6,0.5)),
                 value = ceiling(rnorm(50)*10))

# check counts to see there is one entry where currency =  CHF
count(df, vars="currency")

>currency freq
>1      CHF    1
>2      CNY   13
>3      EUR   16
>4      GBP    6
>5      USD   14


# filter out all entires where site = A, i.e. take subset of df
df <- df[!(df$site=="A"),]

# check counts again to see how this affected the currency frequencies
count(df, vars="currency")

>currency freq
>1      CNY   10
>2      EUR    8
>3      GBP    4
>4      USD   10

# But, the filtered data.frame's levels have not been updated:
levels(df$currency)

>[1] "CHF" "CNY" "EUR" "GBP" "USD"

levels(df$site)

>[1] "A" "B" "C"

期望的输出:

# levels(df$currency) = "CNY" "EUR" "GBP" "USD
# levels(df$site) = "B" "C"

【问题讨论】:

    标签: r dataframe r-factor


    【解决方案1】:

    使用droplevels:

    > df <- droplevels(df)
    > levels(df$currency)
    [1] "CNY" "EUR" "GBP" "USD"
    > levels(df$site)
    [1] "B" "C"
    

    【讨论】:

    • 谢谢,所以我在过滤掉内容后执行此操作,它会从一个因素中删除“未使用的级别,或者更常见的是从数据框中的因素中删除。”?每次对 data.frame 应用过滤器时,我都必须记住降低级别,这似乎有点奇怪。 (但我确信这是有原因的)。你知道为什么会这样吗?
    • @Berkan 因为因子服务于特定的统计/数据目的:可以采用一组特定值的数据。在进行分析时,您经常需要有关所有这些级别的信息,即使它们没有出现。如果这种行为让您不快,您可能应该只使用字符列。
    猜你喜欢
    • 1970-01-01
    • 2018-12-07
    • 2014-09-01
    • 2012-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    相关资源
    最近更新 更多