且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

创建 xts 时间序列

更新时间:2023-02-26 19:24:19

可以将数据读入data.frame,手动解析日期,并将其转换为 xts 对象.如果出现问题,您会更清楚地看到发生了什么.

You can read the data into a data.frame, manually parse the date, and convert it to an xts object. If something goes wrong, you will see more clearly what happens.

d <- read.csv(textConnection(s))
d <- xts( 
  d[,-1], 
  as.POSIXct( 
    as.character(d[,1]), 
    format="'%m/%d/%Y %H:%M:%S'"  # Note the single quotes...
  ) 
)

您也可以使用 read.zoo 来解析 data.frame.

You could also use read.zoo to parse the data.frame.

d <- read.csv(textConnection(s))
d <- read.zoo(d, 
  format="'%m/%d/%Y %H:%M:%S'", 
  FUN=as.POSIXct  # The default is to use dates, not times
)

你也可以直接使用read.zoo.

d <- read.zoo(textConnection(s), 
  sep=",", header=TRUE, 
  format="%m/%d/%Y %H:%M:%S",  # No single quotes: read.zoo calls 
  FUN=as.POSIXct               # read.table, not read.csv:   
)                              # it has different default parameters