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

后端 未结 4 1529
挽巷
挽巷 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:38

    Something different:

    Get the data:

    dat <- data.frame(Property.RealEstate=c(1,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))
    

    Reshape it:

    names(dat)[row(t(dat))[t(dat)==1]]
    #[1] "Property.RealEstate" "Property.Insurance"  "Property.RealEstate"
    #[4] "Property.Insurance"  "Property.CarOther"   "Property.Unknown" 
    

    If you want it cleaned up, do:

    gsub("Property\\.","",names(dat)[row(t(dat))[t(dat)==1]])
    #[1] "RealEstate" "Insurance"  "RealEstate" "Insurance"  "CarOther"   "Unknown" 
    

    If you prefer a factor output:

    factor(row(t(dat))[t(dat)==1],labels=names(dat))
    

    ...and cleaned up:

    factor(row(t(dat))[t(dat)==1],labels=gsub("Property\\.","",names(dat)) )
    

提交回复
热议问题