【问题标题】:Facing difficulty in convert a data.frame to time series object in R?在 R 中将 data.frame 转换为时间序列对象时遇到困难?
【发布时间】:2017-04-14 20:59:57
【问题描述】:

我是 R 语言的新手。我有由标签分隔的文本文件,其中包含每天的销售数据。格式类似于产品 ID、day0、day1、day2、day3 等。下面给出的输入文件部分

productid   0   1   2   3   4   5   6
1           53  40  37  45  69  105 62
4           0   0   2   4   0   8   0
5           57  133 60  126 90  87  107
6           108 130 143 92  88  101 66
10          0   0   2   0   4   0   36
11          17  22  16  15  45  32  36

我使用下面的代码来读取文件

pdInfo <- read.csv("products.txt",header = TRUE, sep="\t")

这允许读取整个文件,变量 x 是一个数据框。我想将 data.frame x 更改为时间序列对象以便进一步处理。在静态测试中,Dickey-Fuller 测试 (ADF) 显示错误。我试过下面的代码

x <- ts(data.matrix(pdInfo),frequency = 1)
adf <- adf.test(x)

  error: Error in adf.test(x) : x is not a vector or univariate time series

提前感谢您的建议

【问题讨论】:

    标签: r time-series read.csv


    【解决方案1】:

    在 R 中,时间序列通常采用“每个日期一行”的形式,而您的数据采用“每个日期一列”的形式。在转换为ts 对象之前,您可能需要转置数据。

    先转置一下:

    y= t(pdInfo)
    

    然后将第一行(作为产品 ID)放入行标题

    colnames(y) = y[1,]
    y= y[-1,] # to drop the first row
    

    这应该可行:

    x = ts(y, frequency = 1)
    

    【讨论】:

    • 谢谢,@lebelinoz。转换为时间序列没有任何错误。但是执行 adf.test(x) 会显示错误,因为“x 不是向量或单变量时间序列”。
    【解决方案2】:
    library(purrr)
    library(dplyr)
    library(tidyr)
    library(tseries)
    
    # create the data
    
    df <- structure(list(productid = c(1L, 4L, 5L, 6L, 10L, 11L), 
                         X0 = c(53L, 0L, 57L, 108L, 0L, 17L), 
                         X1 = c(40L, 0L, 133L, 130L, 0L, 22L), 
                         X2 = c(37L, 2L, 60L, 143L, 2L, 16L), 
                         X3 = c(45L, 4L, 126L, 92L, 0L, 15L), 
                         X4 = c(69L, 0L, 90L, 88L, 4L, 45L), 
                         X5 = c(105L, 8L, 87L, 101L, 0L, 32L), 
                         X6 = c(62L, 0L, 107L, 66L, 36L, 36L)), 
                    .Names = c("productid", "0", "1", "2", "3", "4", "5", "6"), 
                    class = "data.frame", row.names = c(NA, -6L))
    
    # apply adf.test to each productid and return p.value
    
    adfTest <- df %>% gather(key = day, value = sales, -productid) %>%
      arrange(productid, day) %>%
      group_by(productid) %>%
      nest() %>%
      mutate(adf = data %>% map(., ~adf.test(as.ts(.$sales)))
      ,adf.p.value = adf %>% map_dbl(., "p.value")) %>%
      select(productid, adf.p.value) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-05
      • 2014-05-17
      • 2021-01-28
      • 2011-02-04
      • 2019-12-20
      • 1970-01-01
      相关资源
      最近更新 更多