gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:57:29 27 4
gpt4 key购买 nike

我有一组编码为二项式的变量。

   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

我知道这存在: Recoding dummy variable to ordered factor

但是当我尝试使用该帖子中使用的代码时,我收到以下错误:
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))

关于r - 虚拟变量到 R 中的单个分类变量(因子),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29870994/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com