【问题标题】:Loading a csv file as a ts将 csv 文件加载为 ts
【发布时间】:2015-09-22 10:07:32
【问题描述】:

以下是特定股票的每月价格;

Year    Jan     Feb     Mar     Apr     May     Jun     Jul     Aug     Sep     Oct     Nov     Dec
2008    46.09   50.01   48      48      50.15   43.45   41.05   41.67   36.66   25.02   22.98   22
2009    20.98   15      13.04   14.4    26.46   14.32   14.6    11.83   14      14.4    13.07   13.6
2010    15.31   15.71   18.97   15.43   13.5    13.8    14.21   12.73   12.35   13.17   14.59   15.01
2011    15.3    15.22   15.23   15      15.1    14.66   14.8    12.02   12.41   12.9    11.6    12.18
2012    12.45   13.33   12.4    14.16   13.99   13.75   14.4    15.38   16.3    18.02   17.29   19.49
2013    20.5    20.75   21.3    20.15   22.2    19.8    19.75   19.71   19.99   21.54   21.3    27.4
2014    23.3    20.5    20      22.7    25.4    25.05   25.08   24.6    24.5    21.2    20.52   18.41
2015    16.01   17.6    20.98   21.15   21.44   0       0       0       0       0       0       0

我想将数据分解为季节性和趋势数据,但没有得到结果。 如何将数据加载为“ts”类数据以便分解?

【问题讨论】:

  • 呃,这是r 的问题吗?还是Python?还是别的什么?
  • 如何解决这个错误 decompose(se) 中的错误:时间序列没有或少于 2 个周期
  • 请回答我的问题。
  • 你已经尝试了什么?你说你“没有得到结果”。请发布不起作用的代码。 SO 不是代码编写服务。

标签: r csv time-series


【解决方案1】:

这是一个使用tidyr 的解决方案,相当容易访问。

library(dplyr); library(tidyr)
data %>% gather(month, price, -Year) %>% # 1 row per year-month pair, name the value "price"
  mutate(synth_date_txt= paste(month,"1,",Year), # combine month and year into a date string
         date=as.Date(synth_date_txt,format="%b %d, %Y")) %>% # convert date string to date
  select(date, price) # keep just the date and price

#          date price
# 1  2008-01-01 46.09
# 2  2009-01-01 20.98
# 3  2010-01-01 15.31
# 4  2011-01-01 15.30
# 5  2012-01-01 12.45

这会为您提供日期格式的答案(即使您没有指定日期,只指定​​月份和年份)。它应该适用于您的时间序列分析,但如果您真的需要时间戳,您可以使用 as.POSIXct(date)

【讨论】:

  • 我将如何根据下面粘贴的代码应用上面的代码?
【解决方案2】:

迈克,

程序是R,下面是我试过的代码。

sev=read.csv("X7UPM.csv")
se=ts(sev,start=c(2008, 1), end=c(2015,1), frequency=12)
se
se=se[,1]
S=decompose(se)
plot(se,col=c("blue"))
plot(decompose(se))
S.decom=decompose(se,type="mult")
plot(S.decom)
trend=S.decom$trend
trend
seasonal=S.decom$seasonal
seasonal
ts.plot(cbind(trend,trend*seasonal),lty=1:2)
plot(stl(se,"periodic"))

【讨论】:

  • 这应该作为对您问题的编辑,而不是对您问题的回答
猜你喜欢
  • 2015-06-24
  • 2019-10-07
  • 2018-06-06
  • 1970-01-01
  • 2022-01-09
  • 2019-07-13
  • 2017-10-01
相关资源
最近更新 更多