无法将data.frame对象转换为xts对象:产生POSIXlt错误。 (R)

时间:2017-01-14 05:22:59

标签: r time-series xts

我试图将源自.csv的d​​ata.frame对象转换为xts对象。它没有正确转换为xts对象,而是给出错误:

  

as.POSIXlt.character(x,tz,...)出错:字符串不是标准的明确格式

我试图将Date列更改为Date类,但无济于事。这是代码:

library(xts)
mydata <- read.csv("https://sites.google.com/site/jonspinney/home/mba-6693-2017/edhec.csv?attredirects=0&d=1",header=TRUE,sep=",")
mydata$Date <- as.POSIXlt(mydata$Date, format = "%m/%d/%Y")
mydata <- as.xts(mydata)
class(mydata$Date)
class(mydata)

2 个答案:

答案 0 :(得分:4)

当您在数据框上调用泛型函数as.xts时,将调用xts:::as.xts.data.frame。默认情况下,数据框的row.names期望为DateTime,而mydata的第一列为DateTime,而row.names(mydata)则为1, 2, 3, 4, ...,这肯定不是要识别的as.POSIXltas.POSIXct要转换的字符串格式。

由于您已将Date列安排为DateTime格式(POSIXlt格式),因此您可以直接使用xts

oo <- xts(mydata[-1], mydata[[1]])

str(oo)
#An ‘xts’ object on 1993-12-31/2015-11-30 containing:
#  Data: num [1:264, 1:9] 100 100.4 100.5 99.5 97 ...
# - attr(*, "dimnames")=List of 2
#  ..$ : NULL
#  ..$ : chr [1:9] "CA" "SB" "EM" "EMN" ...
#  Indexed by objects of class: [POSIXlt,POSIXt] TZ: 
#  xts Attributes:  
# NULL

class(oo)
#[1] "xts" "zoo"

答案 1 :(得分:2)

您可以使用read.zooas.xts

将其设为单行
myData <- as.xts(read.zoo("https://sites.google.com/site/jonspinney/home/mba-6693-2017/edhec.csv?attredirects=0&d=1",header=TRUE,sep=",", format = "%m/%d/%Y" ))

> str(myData)
An ‘xts’ object on 1993-12-31/2015-11-30 containing:
  Data: num [1:264, 1:9] 100 100.4 100.5 99.5 97 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:9] "CA" "SB" "EM" "EMN" ...
  Indexed by objects of class: [Date] TZ: UTC
  xts Attributes:  
 NULL