简体   繁体   中英

Xts conversion error (do not match the length of object)

I am importing a csv file into R, creating a 3x3 dataframe, and attempting to convert the dataframe to an xts object. But I get error message "do not match the length of object".

#DATSB <- fread("C:/Temp/GoogleDrive/R/temp.csv", select = c("DateTime","Last","Volume"))
#that results in following dput() output:
DATSB <- structure(list(DateTime = c("3/28/2016 20:37", "3/28/2016 20:36","3/28/2016 20:35"), Last = c(1221.7, 1221.8, 1221.9), Volume = c(14L,2L, 22L)), .Names = c("DateTime", "Last", "Volume"), row.names = c(NA,3L), class = "data.frame")

setDF(DATSB)
DATSB$DateTime <- strptime(DATSB$DateTime, format = "%m/%d/%Y %H:%M") 
DATSBxts <- as.xts(DATSB[, -2], order.by = as.Date(DATSB$DateTime, "%Y/%m/%d %H:%M"))

     DateTime     Last     Volume
1 3/28/2016 20:37 1221.7     14
2 3/28/2016 20:36 1221.8      2
3 3/28/2016 20:35 1221.9     22

Exact error message is "Error in as.matrix.data.frame(x) : dims [product 12] do not match the length of object [14]"

Somehow the root of the problem is the column Volume. Without that column, it works. Unfortunately can't figure it out. Thanks for your help!

There was a typo here DATSB[, -2] , correcting it works fine. General theme for xts is,

xts(data[,-date_column], order.by = data[,date_column])

Also coredata(DATSBxts) and index(DATSBxts) are helpful functions

DATSBxts  = xts(DATSB[, -1], order.by = DATSB[,1] ,dateFormat = "%Y/%m/%d %H:%M:%S");rev(DATSBxts)


DATSBxts
#                  Last Volume
#2016-03-28 20:35:00 1221.9     22
#2016-03-28 20:36:00 1221.8      2
#2016-03-28 20:37:00 1221.7     14

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM