我有一个如下所示的数据框:
created_at actor_attributes_email type
3/11/12 7:28 jeremy@asynk.ch PushEvent
3/11/12 7:28 jeremy@asynk.ch PushEvent
3/11/12 7:28 jeremy@asynk.ch PushEvent
3/11/12 7:42 jeremy@asynk.ch IssueCommentEvent
3/11/12 11:06 d.bussink@gmail.com PushEvent
3/11/12 11:06 d.bussink@gmail.com PushEvent
现在我想按月/年重新排列它(仍然按时间排序,仍然保持行的完整性) . 这应该为每个月创建3列,然后将与该月相关的所有数据(created_at,actor_attributes_email和type)放在这3列中,以便获得以下 Headers (对于数据中存在的所有月份):
april_2011_created_at april_2011_actor_attributes_email april_2011_type may_2011_created_at may_2011_actor_attributes_email may_2011_type
我怎样才能在R中实现这一目标?
可以在此处找到包含整个数据集的CSV文件:https://github.com/aronlindberg/VOSS-Sequencing-Toolkit/blob/master/rubinius_rubinius_sequencing/rubinius_6months.csv
这是CSV的第一行 dput()
:
structure(list(created_at = structure(c(1L, 1L, 1L, 2L, 2L, 2L,
3L, 3L, 3L, 4L, 4L, 4L, 5L, 5L, 5L, 6L, 6L, 6L, 7L, 7L, 7L, 8L,
8L, 8L, 9L, 9L, 9L, 10L, 10L, 10L), .Label = c("2012-03-11 07:28:04",
"2012-03-11 07:28:19", "2012-03-11 07:42:16", "2012-03-11 11:06:13",
"2012-03-11 12:46:25", "2012-03-11 13:03:12", "2012-03-11 13:12:34",
"2012-03-11 13:14:52", "2012-03-11 13:30:14", "2012-03-11 13:30:48"
), class = "factor"), actor_attributes_email = structure(c(3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("",
"d.bussink@gmail.com", "jeremy@asynk.ch"), class = "factor"),
type = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L), .Label = c("IssueCommentEvent", "PushEvent"
), class = "factor")), .Names = c("created_at", "actor_attributes_email",
"type"), class = "data.frame", row.names = c(NA, -30L))
其他一些假设是:
-
即使"PushEvent"(例如)重复10次,我需要保留所有这些,因为我将使用R包TraMineR进行序列分析
-
列的长度可以不等
-
不同月份的列之间没有关系
-
某个月内的数据应该按照最早的时间排序
-
来自2011年6月和2012年6月的数据需要分开列
2 回答
Maiasaura提供了一种优雅的方式来完成plyr和lubridate的工作 . 这是在R基础上完成它的稍微不那么优雅的方法 . 但与Maiasaura的不同,这种方式可以最大限度地减少
NA
行的数量 . 每个月的数字NA
行是该月份的行数与任何月份的最大行数之间的差异 .请注意,由于您希望将月份名称附加到3个列名称并填入相应的数据,因此没有数据的所有列都将填充
NA
(这是rbind.fill
的预期行为) .