How to use cast or another function to create a binary table in R

前端 未结 4 405
予麋鹿
予麋鹿 2020-12-02 01:06

I am trying to create a list of factors that have a binary response and have been using cast.

DF2 <- cast(data.frame(DM), id ~ region)
names(DF2)[-1] <         


        
4条回答
  •  青春惊慌失措
    2020-12-02 01:36

    Here's sort of a "tricky" way to do it in one line using table (the brackets are important). Assuming your data.frame is named df:

    (table(df) > 0)+0
    #    region
    # id  1 2 3
    #   1 0 1 1
    #   2 0 1 0
    #   3 1 0 0
    

    table(df) > 0 gives us TRUE and FALSE; adding +0 converts the TRUE and FALSE to numbers.

提交回复
热议问题