在r中转置data.frame

时间:2015-09-11 10:39:09

标签: r

抱歉重复的问题。但我还是找不到答案。 我有一个data.frame:

   Time                 EventName
1  2015-09-10 14:17:21   logged_in
2  2015-09-10 14:17:37 deauthorize
3  2015-09-10 14:17:42   logged_in
4  2015-09-10 14:17:42 deauthorize
5  2015-09-10 14:18:24   logged_in
6  2015-09-10 14:21:06 deauthorize
7  2015-09-10 14:21:13   logged_in
8  2015-09-10 14:21:52 deauthorize
9  2015-09-10 14:51:11   logged_in
10  2015-09-10 15:11:39 deauthorize
11  2015-09-10 15:30:43   logged_in
12  2015-09-10 15:30:44 deauthorize

我希望将其转置为:

                                 1                   2                   3
logged_in      2015-09-10 14:17:21 2015-09-10 14:17:42 2015-09-10 14:18:24 
deauthorize    2015-09-10 14:17:37 2015-09-10 14:17:42 2015-09-10 14:21:06

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

这可能是另一种选择

library(splitstackshape)
cSplit(setDT(dat)[, toString(Time), by=EventName], 'V1', ',')

答案 1 :(得分:2)

您正在寻找aggregate()功能。

说出您的数据框名称是' dat',然后

aggregate(dat$Time, list(dat$EventName),cbind) 

do.call(data.frame, aggregate(. ~ EventName, dat, I))

应该做的工作。

数据

dat <- read.table(header=T, text="   Time                 EventName
1  '2015-09-10 14:17:21'   logged_in
2  '2015-09-10 14:17:37' deauthorize
3  '2015-09-10 14:17:42'   logged_in
4  '2015-09-10 14:17:42' deauthorize
5  '2015-09-10 14:18:24'   logged_in
6  '2015-09-10 14:21:06' deauthorize
7  '2015-09-10 14:21:13'   logged_in
8  '2015-09-10 14:21:52' deauthorize
9  '2015-09-10 14:51:11'   logged_in
10  '2015-09-10 15:11:39' deauthorize
11  '2015-09-10 15:30:43'   logged_in
12  '2015-09-10 15:30:44' deauthorize", stringsAsFactors=FALSE)