split columns into multiple columns

故事扮演 提交于 2021-02-05 12:18:41

问题


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 is my probleme :

reactions__001 reactions__002 reactions__003
25 Like        23 Love                
15 Like        5 Love         3 Haha                          
20 Haha        3 Sad          2 Angry                          

now what i am looking for is to split this data frame like this one

Like Love Haha Sad Angry
25   23   0    0   0      
15   5    3    0   0                         
0    0    20   3   2

i have tried the str_split_fixed(df$reactions__001, " ", 2) but it gives me something like :

 [26,] "1"  "Angry"
 [27,] "3"  "Like" 
 [28,] "0"  ""     
 [29,] ""   ""     
 [30,] "1"  "Like" 
 [31,] "10" "Like"  

回答1:


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)


来源:https://stackoverflow.com/questions/47639358/split-columns-into-multiple-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!