dummy variables to single categorical variable (factor) in R

前端 未结 1 792
陌清茗
陌清茗 2020-12-19 10:25

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            


        
1条回答
  •  醉梦人生
    2020-12-19 10:52

    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

    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)

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

    OR you can do matrix multiplication (contributed by @akrun)

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

    0 讨论(0)
提交回复
热议问题