openAir,96x31时间/日期数据到堆叠数据

时间:2010-12-22 12:42:13

标签: r reshape

我有一个表格,显示当天每个15分钟和每个月的每一天的变量流量,例如:

date,00:00,00:15,00:30,  
01-Nov,123,345,456,  
02-Nov,234,567,890  

我希望将其纳入表格

date,value  
01-Nov 00:00,123  
01-Nov 00:15,345  
...  
02-Nov 00:00,234 

等等。我尝试了reshape,但我不明白如何指定“变化”并不断收到失败消息。

4 个答案:

答案 0 :(得分:2)

试试这个:

require(reshape)
Df <- melt(dataframe,id.vars="date",variable_name="time")
Df <- Df[order(Df$date),]

其中“dataframe”是您正在使用的数据框的名称。如果要组合列日期和时间,可以使用例如:

Df2 <- with(Df,
         data.frame(
           date = paste(date,time),
           value = value
         )
       )

如果这不起作用或不能提供您想要的内容,则必须向我们提供更多信息。

答案 1 :(得分:1)

目前看来,您可能只有日期和数据,但知道要添加的关联时间。动物园包中可能有非常紧凑的方法可以在一行中执行此操作,但这是一个工作示例,显示了5或6步骤过程,在两天内以2小时为间隔(没有时间标签)读取数据,并从宽范围重构将datafrm格式化为具有DateTime分类时间变量的长格式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小时,因为我在美国东部地区。如果您希望在午夜显示时间,则可以向UCT默认值添加4小时的偏移量:

mtst$dt.tm <- as.POSIXct(mtst$dt, tz="EST") +60*120*(0:11) + 60*240

答案 2 :(得分:1)

假设一个连续的规则间隔系列,其中日期为指示格式,以便每行有4 * 24个值,下面给出了一个zooreg系列,使用chron作为日期/时间类:

library(zoo)
library(chron)

DF <- read.csv("myfile.csv", as.is = TRUE)
z <- zooreg(c(t(DF[-1])), start = as.chron(DF[1,1], "%d-%b"), freq = 4 * 24)

as.data.frame(z)会将其变成一个数据框,其中包含行名称中的时间,或data.frame(Time = time(z), Value = coredata(z))将为其自己的列提供时间(尽管您可能最好将其保留为zooreg系列,因为那样会使进一步操作更方便)。

答案 3 :(得分:0)

这是一个xts解决方案:

library(xts)
# Sample data:
Lines <- "date,00:00,00:15,00:30
01-Nov,123,345,456
02-Nov,234,567,890"
con <- textConnection(Lines)
Data <- read.csv(con, stringsAsFactors=FALSE)
close(con)
# times to add to the date for each column
mins <- as.numeric(gsub("[[:alpha:]]","",colnames(Data))) / 0.6 * 3600
# POSIXct index for xts object
idx <- as.POSIXct(Data$date, format="%d-%b")
# Create a list of xts object and rbind them
x <- do.call(rbind, lapply(2:4, function(i) xts(Data[,i], idx+mins[i])))