Convert date-time format for use in xts

2019-08-12 08:43发布

问题:

I am trying to convert my data into an xts but I keep getting a "order.by requires an appropriate time-based object" error so I am trying to convert my date time into the correct format.

My data looks like this:

 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

I have done this as well: data.frame(cbind(theData$Date, theData$Time)) which yields:

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

how to I merge these into one columnn so its:

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

so that I can then put it into an xts()

回答1:

You just need to use paste on the date and time column, then call as.POSIXct on that.

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"))


标签: r xts