R错误:索引不按递增顺序排列

时间:2016-05-23 18:30:47

标签: r csv xts

注意:问题已在下面的评论中解决

在尝试将data.frame转换为找到here中的答案后的xts时,我收到以下错误。

  

.xts(DA [,3:6],index = as.POSIXct(DAINDEX,format =“%m /%d /%Y%H:%M:%S”)出错      index不是递增的顺序

我无法找到有关此错误或如何解决此错误的内容,因此我们将非常感谢您提供帮助。

数据是每日S& P 500,以逗号分隔的格式,具有以下列:“日期”“时间”“打开”“高”“低”“关闭”。

以下是代码:

DA <- read.csv("SNP.csv", header = TRUE, stringsAsFactors = FALSE)
DAINDEX <- paste(DA$Date, DA$Time, sep = " ")
Data.hist <- .xts(DA[,3:6], index = as.POSIXct(DAINDEX, format = "%m/%d/%Y %H:%M:%S", tzone = "GMT"))

根据要求,数据的某些行

structure(list(Date = c("5/20/2016", "5/19/2016", "5/18/2016", 
"5/17/2016", "5/16/2016", "5/13/2016"), Time = c("0:00:00", "0:00:00", 
"0:00:00", "0:00:00", "0:00:00", "0:00:00"), Open = c(2041.880005, 
2044.209961, 2044.380005, 2065.040039, 2046.530029, 2062.5), 
High = c(2058.350098, 2044.209961, 2060.610107, 2065.689941, 
2071.879883, 2066.790039), Low = c(2041.880005, 2025.910034, 
2034.48999, 2040.819946, 2046.530029, 2043.130005), Close = c(2052.320068, 
2040.040039, 2047.630005, 2047.209961, 2066.659912, 2046.609985
)), .Names = c("Date", "Time", "Open", "High", "Low", "Close"
), row.names = c(NA, 6L), class = "data.frame")

以上是dput(head(DA))

的输出

1 个答案:

答案 0 :(得分:0)

最简单的方法是使用常规的xts构造函数而不是.xts。它将检查索引是否正确排序,并在必要时对索引和数据进行排序。

Data.hist <- xts(DA[,3:6], as.POSIXct(DAINDEX, "%m/%d/%Y %H:%M:%S", "GMT"))