Reshape multiple categorical variables to binary response variables

前端 未结 5 1646
醉话见心
醉话见心 2020-12-01 16:55

I am trying to convert the following format:

mydata <- data.frame(movie = c(\"Titanic\", \"Departed\"), 
                     actor1 = c(\"Leo\", \"Jack\"         


        
5条回答
  •  情书的邮戳
    2020-12-01 17:29

    Since they say variety is the spice of life, here's an approach in base R using table:

    table(cbind(mydata[1], 
                actor = unlist(mydata[-1], use.names=FALSE)))
    #           actor
    # movie      Jack Leo Kate
    #   Departed    1   1    0
    #   Titanic     0   1    1
    

    The above output is a matrix of class table. To get a data.frame, use as.data.frame.matrix.

    as.data.frame.matrix(table(
      cbind(mydata[1], actor = unlist(mydata[-1], use.names=FALSE))))
    #          Jack Leo Kate
    # Departed    1   1    0
    # Titanic     0   1    1
    

提交回复
热议问题