簡體   English   中英

使用R中的“汽車”將變量重新編碼為有序因子變量

[英]Recoding variable into an ordered factor variable using 'car' in R

我正在關注car包裝中的文檔,以重新編碼有序因子變量。

例如,在我的data.frame df ,我有一個表示教育程度的變量( BG_x )。 我嘗試將其重新編碼為:

df <- data.frame(
    BG_x = sample(1:8)
)
df$education<-recode(df$BG_x,"1:2='High school or less';3='Some college';4='College';5:8='Grad degree'", levels=c('High school or less','Some college','College','Grad degree'))
table(df$education)

但是,當我檢查分布時,變量似乎按字母順序排列,而不是我在recode命令中指定的順序。 對出什么問題有任何想法嗎?

這不是使用recode的答案,而是顯示了如何使用基數R的factor + levels來做到這一點:

set.seed(1)
df <- data.frame(BG_x = sample(1:8))
df$education <- factor(df$BG_x, ordered = TRUE)
levels(df$education) <- list("High school or less" = 1:2, 
                             "Some college" = 3, "College" = 4, 
                             "Grad degree" = 5:8)
df
#   BG_x           education
# 1    3        Some college
# 2    8         Grad degree
# 3    4             College
# 4    5         Grad degree
# 5    1 High school or less
# 6    7         Grad degree
# 7    2 High school or less
# 8    6         Grad degree
table(df$education)
# 
# High school or less        Some college             College         Grad degree
#                   2                   1                   1                   4

不久前,我為這些步驟(將一個級別分配給多個值)編寫了一個便捷包裝,並將其發布為Gist

您可以按以下方式使用它:

library(devtools)
source_gist("7019545")
df$education <- Factor(df$BG_x, ordered = TRUE, 
                       levels = list("High school or less" = 1:2, 
                                     "Some college" = 3, "College" = 4, 
                                     "Grad degree" = 5:8))

由於原始變量本身並不是一個因素,因此需要包括:

as.factor.result = TRUE

在您的電話中進行recode

您是否考慮過使用plyr的mapvalues函數? 我認為這比汽車的重新編碼要容易得多。

您的情況是:

df$education <- as.factor(mapvalues(df$BG_x, c(1,2,3,4,5,6,7,8), 
c('High school or less','High school or less',"Some college","College","Grad degree",
"Grad degree","Grad degree","Grad degree")))

在我看來,對於此示例來說,這看起來更簡單,但是,當然,如果您有一個因子級別,則希望用recode替換一大堆數字會更好。

暫無
暫無

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

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