How to tidy this dataset?

前端 未结 1 1834
死守一世寂寞
死守一世寂寞 2020-11-30 14:28

I have the dataset below that I want to tidy up.

     user_id                topic may june july august september october
1     192775                 talk           


        
相关标签:
1条回答
  • 2020-11-30 15:20

    With:

    library(tidyr)
    df %>% gather(month, val, may:october) %>% spread(topic, val)
    

    you get:

      user_id     month bark harp talk walk
    1  192775    august    0    0    2  146
    2  192775      july    0    0    0  128
    3  192775      june    0    0    0  123
    4  192775       may    0    0    2  165
    5  192775   october    0    1    1  105
    6  192775 september    0    0    2  113
    

    Another option is to use recast from the reshape2-package:

    library(reshape2)
    recast(df, user_id + variable ~ topic, id.var = c('user_id','topic'))
    
    0 讨论(0)
提交回复
热议问题