如何整理这个数据集? [英] How to tidy this dataset?
本文介绍了如何整理这个数据集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有下面要整理的数据集.
user_id 主题可能是六月七月八月九月十月1 192775 谈话 2 0 0 2 2 12 192775 步行 165 123 128 146 113 1053 192775 树皮 0 0 0 0 0 04 192775 竖琴 0 0 0 0 0 1
我想用 tidyr 塑造成以下格式.
user_id 月谈话走树皮竖琴192775 五月 2 165 0 0192775 六月 0 123 0 0
感谢任何帮助
解决方案
With:
库(tidyr)df %>% 收集(月,val,可能:十月)%>% 传播(主题,val)
你得到:
<块引用> user_id 月树皮竖琴说走1 192775 八月 0 0 2 1462 192775 七月 0 0 0 1283 192775 六月 0 0 0 1234 192775 五月 0 0 2 1655 192775 十月 0 1 1 1056 192775 九月 0 0 2 113
<小时>
另一种选择是使用 reshape2
包中的 recast
:
库(reshape2)重铸(df,user_id + 变量~主题,id.var = c('user_id','topic'))
I have the dataset below that I want to tidy up.
user_id topic may june july august september october
1 192775 talk 2 0 0 2 2 1
2 192775 walk 165 123 128 146 113 105
3 192775 bark 0 0 0 0 0 0
4 192775 harp 0 0 0 0 0 1
I want to use tidyr to shape into the below format.
user_id month talk walk bark harp
192775 may 2 165 0 0
192775 june 0 123 0 0
Any help is appreciated
解决方案
With:
library(tidyr)
df %>% gather(month, val, may:october) %>% spread(topic, val)
you get:
user_id month bark harp talk walk 1 192775 august 0 0 2 146 2 192775 july 0 0 0 128 3 192775 june 0 0 0 123 4 192775 may 0 0 2 165 5 192775 october 0 1 1 105 6 192775 september 0 0 2 113
Another option is to use recast
from the reshape2
-package:
library(reshape2)
recast(df, user_id + variable ~ topic, id.var = c('user_id','topic'))
这篇关于如何整理这个数据集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文