【问题标题】:Convert data frame to time series R将数据帧转换为时间序列 R
【发布时间】:2019-08-23 08:40:24
【问题描述】:

我有以下数据

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'.

【问题讨论】:

    标签: r time-series


    【解决方案1】:

    如果你想使用 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)
    

    这里有一些例子:Converting Date formats in R

    【讨论】:

      【解决方案2】:

      R 有多种表示时间序列的方式。由于您只使用日期和总和,因此我为您创建了一个示例时间序列。我选择随机日期和数字。

      征集包裹

      library(xts)
      

      创建数据框

      data_sample <- data.frame(
              date = as.Date(c("2012-01-01","2013-01-01","2014-01-01", )),  
              sum1 = c(3322.01, 6652.77, 3311.12))
      
      head(data_sample)
      

      将日期转换为 R 可以理解的格式。

      rdate<- as.Date(data_sample$date, "%m/%d/%y")  
      fix(rdate)
      

      绘制图表

      plot(data_sample$sum1~rdate,type="l",col="red")
      

      执行上述代码将给出以下输出。

      【讨论】:

        【解决方案3】:

        假设data_sample 在最后的注释中重复显示,使用read.zoo 转换为动物园类的时间序列,然后以该形式使用它或将其转换为其他类,例如 xts 或 ts使用适当的 as.* 函数。这里我们使用yearmon类来表示索引,因为它直接表示没有日的年月。这个类将在zoo和xts中使用,转换为ts时会进行适当的转换。

        library(xts) # this also loads zoo
        
        z <- read.zoo(data_sample, FUN = as.yearmon, format = "%b %Y")
        
        as.xts(z)
        as.ts(z)
        

        日期

        也可以使用 Date 类作为 zoo 和 xts 中的索引,但不能很好地与 ts 类一起使用。使用 Date 类意味着连续点之间的距离会根据每月的天数而变化,而不是定期间隔的系列,因此将 Date 用于每月数据通常对预测没有用处。

        zd <- aggregate(z, as.Date, c)
        xd <- as.xts(zd)
        

        注意

        以可重现的形式输入

        Lines <- "date,Sum 
        1,Feb 2015,3322.01 
        2,Mar 2015,6652.77 
        3,Apr 2015,3311.12 "
        data_sample <- read.csv(text = Lines)
        

        【讨论】:

          【解决方案4】:
          air1 <- type.convert(.preformat.ts(AirPassengers))
          airpassengers <- as.data.frame(air1)
           
           View(airpassengers)
           class(airpassengers)
          [1] "data.frame"
          

          它将时间序列数据转换为数据帧。

          【讨论】:

            猜你喜欢
            • 2020-03-14
            • 1970-01-01
            • 2018-02-08
            • 2017-12-13
            • 2022-11-01
            • 1970-01-01
            • 2020-08-08
            相关资源
            最近更新 更多