split columns into multiple columns

后端 未结 1 739
再見小時候
再見小時候 2021-01-29 08:44

i have been struggled with how to split multiple columns into multiple columns using R but with no result, i have tried many tricks on Stackoverflow and it doesn\'t work. here i

1条回答
  •  野的像风
    2021-01-29 09:00

    xx$id = 1:nrow(xx)
    library(tidyr)
    library(dplyr)
    xxlong = gather(xx, key = "key", value = "value",-id)
    xxlong = separate(xxlong, value, into = c("num", "attr"))
    xxlong %>% na.omit %>% select(-key) %>%
        spread(key = attr, value = num, fill = 0)
    #   id Angry Haha Like Love Sad
    # 1  1     0    0   25   23   0
    # 2  2     0    3   15    5   0
    # 3  3     2   20    0    0   3
    

    I'll leave the reordering of the columns to you.


    Using this data:

    xx = read.table(text = "reactions__001 reactions__002 reactions__003
    '25 Like'        '23 Love'                
    '15 Like'        '5 Love'         '3 Haha'                          
    '20 Haha'        '3 Sad'          '2 Angry'  ", header = T, fill = T)
    

    0 讨论(0)
提交回复
热议问题