首页 > 解决方案 > 将数据帧转换为时间序列 R

问题描述

我有以下数据

data_sample
        date         Sum 
1  Feb 2015      3322.01 
2  Mar 2015      6652.77 
3  Apr 2015      3311.12 
etc

我需要转换为时间序列进行预测

 > data <- xts(data_sample[,-1], order.by=as.Date(data_sample[,1], "%Y %m"))
Error in 1 - frac : non-numeric argument to binary operator
> data <- xts(data_sample[,-1], order.by=as.Date(data_sample[,1], "%m %Y"))
Error in 1 - frac : non-numeric argument to binary operator



> ts_ts(ts_long(data_sample))
Error in guess_time(x) : 
  No [time] column detected. To be explict, name time column as 'time'.

标签: rtime-series

解决方案


如果你想使用 as.Date(),你必须指定完整的日期。只需在每个条目的末尾添加 01。

date <- c("Feb 2015", "Mar 2015", "Apr 2015")
date <- as.Date(paste(date, "01"), format="%b %Y %d")

您可以按如下方式将它们转换回来,

format(date, "%b %Y")

或使用来自动物园图书馆的 as.yearmon,

library("zoo")
as.yearmon(date)

这里有一些例子:在 R 中转换日期格式


推荐阅读