【问题标题】:Converting Data Frame to Time Series using R使用 R 将数据帧转换为时间序列
【发布时间】:2018-02-08 21:03:16
【问题描述】:

我有一个格式如下的 csv。

  Date      Sales
 1/3/2005     800
 1/4/2005    9000
 1/5/2005    1300
 1/6/2005     400
 1/7/2005     100
 1/8/2005     190

我尝试使用以下方法将其转换为时间序列格式:

ts(dataframe)

但它给出了一个奇怪的输出。任何帮助或指导表示赞赏。

【问题讨论】:

  • 第一行是1月3日还是3月1日?
  • 我想你只是想要这样的东西dataframe$Date <- as.Date(dataframe$Date, "%d/%m/%Y"),还是我误会了?
  • 一月三日,所以月/日/年。
  • 我在尝试转换时收到以下错误。 as.date(h.data, format = "%m/%d/%y") 中的错误:无法强制转换为日期格式
  • 使用上面的 Y:as.Date(h.data, format = "%m/%d/%Y") 这对我有用。

标签: r time time-series series


【解决方案1】:

如果日期格式为 m/d/yyyy(已修改):

df <- read.table(header = TRUE, text = "Date      Sales
 1/3/2005     800
 1/4/2005    9000
 1/5/2005    1300
 1/6/2005     400
 1/7/2005     100
 1/8/2005     190",  stringsAsFactors = FALSE)

mydate <- function(x) {
  c(year = as.numeric(unlist(strsplit(x, "/"))[3]),
    month = as.numeric(unlist(strsplit(x, "/"))[1]),
    day = as.numeric(unlist(strsplit(x, "/"))[2]))
}

(myts <- ts(df$Sales, 
            start = mydate(head(df$Date, 1)),
            freq = 365.25))

【讨论】:

  • 根据问题下的讨论是m/d/yyyy。
猜你喜欢
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
  • 2017-04-09
  • 2017-12-13
  • 2022-11-01
  • 1970-01-01
相关资源
最近更新 更多