如何将带有日期列的 time.series 对象写入 R 中的 excel 文件?

How to write time.series object with date column to an excel file in R?

有几个函数可以将data.frames写入excel,例如write.xls 来自 xlsx 包。但是,当我编写时间序列时,它会保存行名称为 1、2、3 的数据,而不是日期。如何将日期保存为行名?

谢谢!

例如,您可以使用 lubridate 包中的 as.yearmon

require(lubridate)
require(zoo)

col_names <- as.yearmon(time(my_ts)) 

现在您可以创建一个新的数据框:

data.frame(col_names, my_ts)

制作一个包含两列的数据框 - 时间序列中的日期和值。

# Retrieve start date and end date from time series
start_date <- as.Date(start(tsobject)[1])
end_date <- start_date+length(tsobject)-1

# Make a data frame with two columns - date and value
df <- data.frame(date=seq(from=start_date, to=end_date, by=1),
                 value=tsobject)

# Write data to excel
write.xlsx(df, filename)