我一直在努力研究如何使用R将多个列拆分成多个列,但是没有结果,我在Stackoverflow上尝试了很多技巧并且它不起作用。这是我的问题:
reactions__001 reactions__002 reactions__003
25 Like 23 Love
15 Like 5 Love 3 Haha
20 Haha 3 Sad 2 Angry
现在我要找的是像这样分割这个数据框
Like Love Haha Sad Angry
25 23 0 0 0
15 5 3 0 0
0 0 20 3 2
我试过了str_split_fixed(df$reactions__001, " ", 2)
,但它给了我类似的东西:
[26,] "1" "Angry"
[27,] "3" "Like"
[28,] "0" ""
[29,] "" ""
[30,] "1" "Like"
[31,] "10" "Like"
答案 0 :(得分:3)
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
我会将列重新排序给你。
使用此数据:
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)