简体   繁体   English

R中的单个分类变量(因子)的虚拟变量

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

I have a set of variables coded as binomial. 我有一组编码为二项式的变量。

   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           

I would like to merge the variables (VALUE_1, VALUE_2...VALUE_8) into one single ordered factor, while conserving the column (Pre) as is, duch that the data would look like this: 我想将变量(VALUE_1,VALUE_2 ... VALUE_8)合并为一个单独的有序因子,同时保留列(Pre),因为数据看起来像这样:

  Pre VALUE
1  1  VALUE_6
2  1  VALUE_5
3  1  VALUE_5

Or even better: 甚至更好:

  Pre VALUE
1  1  6
2  1  5
3  1  5

I am aware that this exists: Recoding dummy variable to ordered factor 我知道这存在:将虚拟变量重新编码为有序因子

But when I try the code used in that post, I receive the following error: 但是,当我尝试该帖子中使用的代码时,我收到以下错误:

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?

Any help would be appreciated 任何帮助,将不胜感激

A quick solution would be something like 一个快速的解决方案就是这样的

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

OR if you want the actual names of the columns (as Pointed by @BondedDust), you can use the same methodology to extract them 或者如果你想要列的实际名称(由@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

OR you can use your own which strategy in the following way (btw, which is vectorized so no need in using apply with a margin of 1 on it) 或者您可以使用自己的which策略以下列方式(顺便说一句, which是矢量所以在使用无需apply与1就可以了保证金)

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

OR you can do matrix multiplication (contributed by @akrun) 或者你可以做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