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),duch数据看起来像这样:
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
我知道这存在:Recoding dummy variable to ordered factor
但是当我尝试 post 中使用的代码时,我收到以下错误:
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
OR 如果您想要列的实际名称(如@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 您可以通过以下方式使用自己的 which
策略(顺便说一句,which
是矢量化的,因此无需使用 apply
上边距为 1)
cbind(df[1], VALUE = factor(which(df[-1] == 1, arr.ind = TRUE)[, 2], ordered = TRUE))
OR 你可以做 matrix
乘法(由@akrun 提供)
cbind(df[1], VALUE = factor(as.matrix(df[-1]) %*% seq_along(df[-1]), ordered = TRUE))
我有一组编码为二项式的变量。
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),duch数据看起来像这样:
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
我知道这存在:Recoding dummy variable to ordered factor
但是当我尝试 post 中使用的代码时,我收到以下错误:
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
OR 如果您想要列的实际名称(如@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 您可以通过以下方式使用自己的 which
策略(顺便说一句,which
是矢量化的,因此无需使用 apply
上边距为 1)
cbind(df[1], VALUE = factor(which(df[-1] == 1, arr.ind = TRUE)[, 2], ordered = TRUE))
OR 你可以做 matrix
乘法(由@akrun 提供)
cbind(df[1], VALUE = factor(as.matrix(df[-1]) %*% seq_along(df[-1]), ordered = TRUE))