2012-12-25 60 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)