as.xts 函数中的日期格式

dateFormat in as.xts function

我想将 R 中的数据集 "co2" 转换为 CSV。 我的代码如下:

require(xts)
require(zoo)
co2_xts <- as.xts(co2)
write.zoo(co2_xts, file="demo.csv",sep=",")

这很好用。但是时间索引显示为 "ene. 1959"(它是西班牙语)。如果可能的话,我希望索引采用格式“%B %Y”。如果我使用:

co2_xts <- as.xts(co2,dateFormat="%B %Y")

这会引发错误:

Error in `as.%B %Y`(c(1959, 1959.08333333334, 1959.16666666668, 1959.25000000002,  : 
could not find function "as.%B %Y"

那么我怎样才能达到我想要的呢?

您可以在使用indexFormat函数创建xts后调整索引格式。

在这种情况下:

indexFormat(co2_xts) <- "%B %Y" 

请注意,这只会更改显示格式。

您是否考虑过 timetk 包并保存小标题?

require(timetk)
co2_tbl <- tk_tbl(co2, start = start(co2), freq = 12)

然后使用更通用的 write.csv,或一种更快的方法,例如fread::write_csv 如果是长文件:

write.csv(co2_tbl, file="demo.csv", row.names=FALSE)