2015-07-04 50 views
0

以下是特定股票的每月價格;將csv文件加載爲ts

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」類數據加載,以便分解它?

+0

呃,這是一個'r'問題嗎?還是'Python'?或者是其他東西? –

+0

如何解決此錯誤分解(se)中的錯誤:時間序列沒有或少於2個週期 – Emeka

+0

請回答我的問題。 –

回答

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)

+0

基於我粘貼的代碼,我將如何應用上面的代碼? – Emeka

0

麥克,

程序爲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")) 
+0

這應該作爲編輯你的問題,而不是你的問題的答案 – C8H10N4O2