2012-12-25 91 views
0

我有一个看起来像这样的数据库:重塑从数据帧一列排成几列,使用R

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 

回答

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 
2

您可以使用功能xtabs

xtabs(~ date + stations, df)