我有一张表格,显示一天中每 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
,但我不明白如何指定“变化”并不断收到失败消息。
尝试这个 :
require(reshape)
Df <- melt(dataframe,id.vars="date",variable_name="time")
Df <- Df[order(Df$date),]
其中“数据框”是您正在使用的数据框的名称。如果要合并列日期和时间,可以使用例如:
Df2 <- with(Df,
data.frame(
date = paste(date,time),
value = value
)
)
如果这不起作用或不能提供您想要的,您必须向我们提供更多信息。
假设具有指定格式的日期的连续规则间隔系列,因此每行有 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 系列,因为这样可以更方便地进行进一步操作)。
目前看来,您可能只有日期和数据,但知道要添加的相关时间。zoo 包中可能有非常紧凑的方法可以在一行中执行此操作,但这里有一个工作示例,显示了一个 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 小时的偏移,因为我在美国东部 tz。如果您想让时间显示为午夜,您可以在 UCT 默认值中添加 4 小时的偏移量:
mtst$dt.tm <- as.POSIXct(mtst$dt, tz="EST") +60*120*(0:11) + 60*240
这是一个 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])))