0

我有一个看起来像这样的数据库:

start<-as.POSIXct("2012-01-15")
interval<-60
end<-start+as.difftime(31,units="days")
date<-seq(from=start,by=interval*60, to=end) # date/time information
l<-length(date)

stations<-as.factor(rep(1:3,len=l)) # stations
df<-data.frame(date,stations) # data frame

我想要的是将此数据帧中的站列重塑为几列(在本例中为 3 列),并计算每个站在每个日期/时间行中记录的时间数。但是,我想保留数据库中的原始日期/时间列。如果一个电台没有记录在一个特定的日期/时间,那么我想分配一个零值。

理想情况下,我想要这样的输出:

date              1   2   3
2012-01-15 0:00   1   0   0
2012-01-15 1:00   0   1   0
2012-01-15 2:00   0   0   1
2012-01-15 3:00   1   0   0
2012-01-15 4:00   0   1   0
2012-01-15 5:00   0   0   1
2012-01-15 6:00   1   0   0
2012-01-15 7:00   0   1   0
2012-01-15 8:00   0   0   1
2012-01-15 9:00   1   0   0
2012-01-15 10:00  0   1   0
4

2 回答 2

2

您可以尝试使用dcast()库中的函数reshape2

library(reshape2)
dcast(df,date~stations,length)
                   date 1 2 3
1   2012-01-15 00:00:00 1 0 0
2   2012-01-15 01:00:00 0 1 0
3   2012-01-15 02:00:00 0 0 1
4   2012-01-15 03:00:00 1 0 0
于 2012-12-25T11:44:00.620 回答
2

您可以使用该功能xtabs

xtabs( ~ date + stations, df)
于 2012-12-25T12:09:11.893 回答