r-转换日期-时间格式以在xts中使用



我试图将我的数据转换为xts,但我一直收到"order.by需要一个适当的基于时间的对象"错误,所以我试图将日期时间转换为正确的格式。

我的数据如下:

 Date      Time      Value
 20090202  9:30      1
 20090202  9:31      2
 20090202  9:32      3
 20090202  9:33      4
 20090202  9:34      5
 20090202  9:35      6

我也做过:data.frame(cbind(data$Date,data$Time)),它产生:

    1         2          
 20090202    09:30
 20090202    09:31
 20090202    09:32
 20090202    09:33
 20090202    09:34
 20090202    09:35

如何将这些合并为一列

       1
 20090202 09:30
 20090202 09:31
 20090202 09:32
 20090202 09:33
 20090202 09:34
 20090202 09:35

这样我就可以把它放进一个xts()

您只需要在日期和时间列上使用paste,然后在此列上调用as.POSIXct

theData <- read.table(text="Date      Time      Value
 20090202  9:30      1
 20090202  9:31      2
 20090202  9:32      3
 20090202  9:33      4
 20090202  9:34      5
 20090202  9:35      6", header=TRUE, as.is=TRUE)
theData$DateTime <- paste(theData$Date, theData$Time)
xts(theData$Value, as.POSIXct(theData$DateTime, format="%Y%m%d %H:%M"))

最新更新