简体   繁体   中英

split columns into multiple columns

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"  
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM