将 Excel 中的一列日期读入 zoo(或 xts)

Read a column of dates from Excel into zoo (or xts)

我有一列日期,从 Excel 作为 CSV 导出到数据框中,"import dataset..." 中的默认类型“...来自 CSV”,即 d<-read_csv(data.csv)。 我喜欢从数据框中创建一个动物园 and/or xts 对象。

数据为:

30/04/2016
31/05/2016
30/06/2016

我收到以下错误:

dates <- c('30/04/2016','31/05/2016','30/06/2016')
d <- dates
z <- read.zoo(d)

Error in read.zoo(d) : index has bad entry at data row 1

z <- read.zoo(d, FUN = as.Date())

Error in as.Date() : argument "x" is missing, with no default

z <- read.zoo(d, FUN = as.Date(format="%d/%m/%Y"))

Error in as.Date(format = "%d/%m/%Y") : argument "x" is missing, with no default

或者,如果我直接读入 zoo 格式的 arguemnt,我会得到一个不同的错误:

ts.z <- read.zoo(d,index=1,tz='',format="%d/%m/%Y")

Error in read.zoo(d, index = 1, tz = "", format = "%d/%m/%Y") :
index has bad entry at data row 1

错误条目第 1 行的错误是什么?指定 FUN = 的正确方法是什么? 类 的正确输入和 read.zoo 的区别是什么?

来自 ?read.zoo 关于 file 参数:

character string or strings giving the name of the file(s) which the data are to be read from/written to. See read.table and write.table for more information. Alternatively, in read.zoo, file can be a connection or a data.frame (e.g., resulting from a previous read.table call) that is subsequently processed to a "zoo" series.

您的示例中出现的问题是 d 既不是文件名、连接也不是 data.frame。您必须将其包装在 data.frame().

一个工作示例:

z <- read.zoo(data.frame(dates), FUN = as.Date, format='%d/%m/%Y')

给出:

> z

2016-04-30
2016-05-31
2016-06-30
> class(z)
[1] "zoo"

使用的输入数据:

dates <- c('30/04/2016','31/05/2016','30/06/2016')