簡體   English   中英

如何重新調整因子變量的級別而不將其轉換為 R 中的整數?

[英]How to relevel the levels of a factor variable without transforming it to integer in R?

我想將下面的四個類別轉換為兩個新類別: zona_a包含(north_east & nothern_central)zone_b包含其他兩個類別。 有沒有辦法在不經歷將變量轉換為整數並使用ifelse函數的麻煩的情況下實現這一ifelse

library(plm)
data("Males")

table(Males$residence)

 rural_area      north_east  nothern_central           south 
     85             733             964            1333 

在這里,您有一個tidyverse解決方案,希望對您有所幫助:

library(tidyverse)
Males <- Males %>% 
  mutate(residence = factor(case_when(residence %in% c("north_east", "nothern_central") ~ "zone_a",
                                      residence %in% c("rural_area", "south") ~ "zone_b")))

levels()函數是解決此問題的一種方法,因為它允許您設置新的因子水平。 您還可以對factor()labels參數執行類似操作(未顯示)。

如果使用levels()您必須注意根據當前順序設置新級別,因此我總是先查看它們。

下面是一個例子:

# Check current levels
levels(Males$residence)
#> [1] "rural_area"      "north_east"      "nothern_central" "south"

# Set new levels in correct order
levels(Males$residence) = c("zone_b", "zone_a", "zone_a", "zone_b")

# Check that this worked
table(Males$residence)
#> 
#> zone_b zone_a 
#>   1418   1697

一種“更安全”的方法,您必須明確地將舊值和新值配對,可以通過使用fct_collapse()forcats來完成。 (感謝@camille 將這個函數指向fct_recode() 。)

library(forcats)
data(Males)
Males$residence = fct_collapse(Males$residence,
             zone_a = c("north_east", "nothern_central"),
             zone_b = c("rural_area", "south")
)

table(Males$residence)
#> 
#> zone_b zone_a 
#>   1418   1697

reprex 包(v2.0.1) 於 2021 年 11 月 2 日創建

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM