Reshaping a data.frame so a column containing multiple features becomes multiple binary columns

后端 未结 4 781
滥情空心
滥情空心 2021-01-27 08:06

I have a dataframe like this

df <-data.frame(id = c(1,2),
                value = c(25,24),
                features = c(\"A,B,D,F\",\"C,B,E\"))

print(df)

i         


        
4条回答
  •  青春惊慌失措
    2021-01-27 09:06

    You can do:

    library(splitstackshape)
    library(qdapTools)
    
    df1 = data.frame(cSplit(df, 'features', sep=',', type.convert=F))
    cbind(df1[1:2], mtabulate(as.data.frame(t(df1[-c(1,2)]))))
    
    #   id value A B C D E F
    #1:  1    25 1 1 0 1 0 1
    #2:  2    24 0 1 1 0 1 0
    

提交回复
热议问题