简体   繁体   English

将列拆分为多列

[英]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. 我一直在努力使用R将多列拆分为多列,但没有结果,我在Stackoverflow上尝试了许多技巧,但它不起作用。 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 : 我已经尝试过str_split_fixed(df$reactions__001, " ", 2)但是它给了我类似的东西:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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