R: Converting multiple binary columns into one factor variable whose factors are binary column names

后端 未结 4 1522
挽巷
挽巷 2021-01-03 02:09

I am a new R user. Currently I am working on a dataset wherein I have to transform the multiple binary columns into single factor column

Here is the example:

4条回答
  •  悲&欢浪女
    2021-01-03 02:18

    Alternately, you can just do it in the naïve way. I think it's more transparent than any of the other suggestions (including my other suggestion).

    df=data.frame(Property.RealEstate=c(0,0,1,0,0,0),
                  Property.Insurance=c(0,1,0,1,0,0),
                  Property.CarOther=c(0,0,0,0,1,0),
                  Property.Unknown=c(0,0,0,0,0,1))
    
    propcols=c("Property.RealEstate", "Property.Insurance", "Property.CarOther", "Property.Unknown")
    
    df$Property=NA
    
    for(colname in propcols)({
      coldata=df[,colname]
      df$Property[which(coldata==1)]=colname
    })
    
    df$Property=gsub("Property.","",df$Property,fixed=T)
    

提交回复
热议问题