R - Convert various dummy/logical variables into a single categorical variable/factor from their name

后端 未结 3 1093
别那么骄傲
别那么骄傲 2021-02-04 16:28

My question has strong similarities with this one and this other one, but my dataset is a little bit different and I can\'t seem to make those solutions work. Please excuse me i

3条回答
  •  一生所求
    2021-02-04 17:06

    You can also try:

    colnames(df)[2:5][max.col(!is.na(df[,2:5]))]
    #[1] "conditionA" "conditionB" "conditionC" "conditionD" "conditionA"
    

    The above works if one and only one column has a value other than NA for each row. If the values of a row can be all NAs, then you can try:

    mat<-!is.na(df[,2:5])
    colnames(df)[2:5][max.col(mat)*(NA^!rowSums(mat))]
    

提交回复
热议问题