目前看來您可能只有日期和數據,但知道您要添加的關聯時間。動物園包中可能有非常緊湊的方法,可以在一行中完成此操作,但這裏有一個工作示例,顯示5或6個步驟過程,在兩天內以2小時間隔讀取數據(沒有時間標籤),並從寬範圍重構格式datafrm以長格式datafrm與日期時間入級時間變量:
require(reshape2)
txt<-"01-Nov,123,345,456,345,565,345,464,345, 123,345,456,345
02-Nov,234,567,890,345,565,345,464,345, 123,345,456,345"
tstdf <- read.table(textConnection(txt), header=FALSE, sep=",")
mtst <- melt(tstdf, id.vars="V1",variable_name="time")
mtst$dt <- as.Date(mtst$V1, format="%d-%B")
mtst <- cbind(mtst, tm= 120*(0:11))
mtst$dt.tm <- as.POSIXct(mtst$dt) +60*120*(0:11)
'data.frame': 24 obs. of 6 variables:
$ V1 : Factor w/ 2 levels " 02-Nov","01-Nov": 2 1 2 1 2 1 2 1 2 1 ...
$ time : Factor w/ 12 levels "V2","V3","V4",..: 1 1 2 2 3 3 4 4 5 5 ...
$ value: int 123 234 345 567 456 890 345 345 565 565 ...
$ dt :Class 'Date' num [1:24] 14914 14915 14914 14915 14914 ...
$ tm : num 0 120 240 360 480 600 720 840 960 1080 ...
$ dt.tm: POSIXct, format: "2010-10-31 20:00:00" "2010-11-01 22:00:00" ...
你會變化的Tm =分配到第15(0:95),並有4小時上顯示的時間偏移,因爲我在美國東部tz。如果你想獲得的時間顯示爲在午夜,你可以添加4小時的偏移量,UCT默認:
mtst$dt.tm <- as.POSIXct(mtst$dt, tz="EST") +60*120*(0:11) + 60*240
一些玩具數據和你嘗試的代碼會有幫助 – 2010-12-22 12:49:21