簡體   English   中英

R中的單個分類變量(因子)的虛擬變量

[英]dummy variables to single categorical variable (factor) in R

我有一組編碼為二項式的變量。

   Pre VALUE_1 VALUE_2 VALUE_3 VALUE_4 VALUE_5 VALUE_6 VALUE_7 VALUE_8 
1   1       0       0       0       0       0       1       0       0       
2   1       0       0       0       0       1       0       0       0       
3   1       0       0       0       0       1       0       0       0       
4   1       0       0       0       0       1       0       0       0           

我想將變量(VALUE_1,VALUE_2 ... VALUE_8)合並為一個單獨的有序因子,同時保留列(Pre),因為數據看起來像這樣:

  Pre VALUE
1  1  VALUE_6
2  1  VALUE_5
3  1  VALUE_5

甚至更好:

  Pre VALUE
1  1  6
2  1  5
3  1  5

我知道這存在:將虛擬變量重新編碼為有序因子

但是,當我嘗試該帖子中使用的代碼時,我收到以下錯誤:

PA2$Factor = factor(apply(PA2, 1, function(x) which(x == 1)), labels = colnames(PA2)) 

Error in sort.list(y) : 'x' must be atomic for 'sort.list'
Have you called 'sort' on a list?

任何幫助,將不勝感激

一個快速的解決方案就是這樣的

Res <- cbind(df[1], VALUE = factor(max.col(df[-1]), ordered = TRUE))
Res
#   Pre VALUE
# 1   1     6
# 2   1     5
# 3   1     5
# 4   1     5

str(Res)
# 'data.frame':  4 obs. of  2 variables:
# $ Pre  : int  1 1 1 1
# $ VALUE: Ord.factor w/ 2 levels "5"<"6": 2 1 1 1

或者如果你想要列的實際名稱(由@BondedDust指出),你可以使用相同的方法來提取它們

factor(names(df)[1 + max.col(df[-1])], ordered = TRUE)
# [1] VALUE_6 VALUE_5 VALUE_5 VALUE_5
# Levels: VALUE_5 < VALUE_6

或者您可以使用自己的which策略以下列方式(順便說一句, which是矢量所以在使用無需apply與1就可以了保證金)

cbind(df[1], VALUE = factor(which(df[-1] == 1, arr.ind = TRUE)[, 2], ordered = TRUE))

或者你可以做matrix乘法(由@akrun提供)

cbind(df[1], VALUE = factor(as.matrix(df[-1]) %*% seq_along(df[-1]), ordered = TRUE))

暫無
暫無

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

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