简单的data.frame重塑 [英] simple data.frame reshape

查看:267
本文介绍了简单的data.frame重塑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚从长时间的写作中回到了R,而且我记得如何重塑数据的真正问题。
我知道我想做的很简单,但由于某种原因我今天晚上很笨,并且混淆了自己的融化和重塑。
如果有人能够快速指出我正确的方向,那将是非常感激的。



我有一个数据框:

 人周年
personA 6 1
personA 22 1
personA 41 1
personA 42 1
personA 1 2
personA 23 2
personB 8 2
personB 9 2
....
personN xy

我想最终得到年度和个人的事件计数:
(以便我可以为每个人绘制快速线图多年)



例如

  person year1 year2 
personA 4 2
personB 0 2

非常感谢您阅读。

解决方案

我可能会使用 reshape2 package和 dcast 函数,因为它在一个步骤中处理重新整形和聚合: / p>

  library(reshape2)
> dcast(person〜year,value.var =year,data = dat)
汇总功能缺失:预设长度
人1 2
1人A 4 2
2人B 0 2


I've just come back to R from a long hiatus writing and I'm having some real problems remembering how to reshape data. I know that what I want to do is easy, but for some reason I'm being dumb tonight and have confused myself with melt and reshape. If anyone could quickly point me in the right direction it would be hugely appreciated.

I have a dataframe as such:

person    week    year   
personA   6       1
personA   22      1
personA   41      1
personA   42      1
personA   1       2
personA   23      2
personB   8       2
personB   9       2
....
personN   x       y

I want to end up with a count of events by year and by person: (so that I can plot a quick line graph for each person over the years )

e.g.

person    year1    year2
personA   4        2
personB   0        2

Many thanks for reading.

解决方案

I would probably use reshape2 package and the dcast function since it handles both the reshaping and aggregation in one step:

library(reshape2)
> dcast(person ~ year, value.var = "year", data = dat)
Aggregation function missing: defaulting to length
   person 1 2
1 personA 4 2
2 personB 0 2

这篇关于简单的data.frame重塑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆