【问题标题】:dummy variables to single categorical variable (factor) in RR中单个分类变量(因子)的虚拟变量
【发布时间】:2015-07-04 10:41:17
【问题描述】:

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

   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?

任何帮助将不胜感激

【问题讨论】:

    标签: r factors


    【解决方案1】:

    一个快速的解决方案是这样的

    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 是矢量化的,因此无需使用带有 1 边距的apply

    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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-25
      • 2018-03-29
      • 2021-07-27
      • 1970-01-01
      • 2021-08-23
      • 2015-07-31
      相关资源
      最近更新 更多