我有以下数据格式如下
Date : Value
1995Q3: 8,540.40
1995Q4: 9,573.90
1996Q1: 8,856.40
1996Q2: 8,841.30
.......
有80个观察结果 Q1,Q2,Q3和Q4代表了今年的四季度。
我很困惑如何使用这样的数据在R中创建时间序列图。我已经探索过互联网,但没有找到任何有用的东西。
答案 0 :(得分:0)
这就是你要找的东西吗?
options(stringsAsFactors = F)
data = data.frame(Date = c("1995Q3","1995Q4","1996Q1","1996Q2"),
Value = c(8540.40, 9573.90, 8856.40, 8841.30))
data$Date = gsub(pattern = "Q1", replacement = "/1/1", data$Date)
data$Date = gsub(pattern = "Q2", replacement = "/4/1", data$Date)
data$Date = gsub(pattern = "Q3", replacement = "/7/1", data$Date)
data$Date = gsub(pattern = "Q4", replacement = "/10/1", data$Date)
data$Date = strptime(data$Date , format = "%Y/%m/%d")
plot(x = 1:4, y = data$Date, type = "l")
答案 1 :(得分:0)
此代码将执行此操作
# Your data
a<- rbind(c("1995Q3", 8540.40),c("1995Q4", 9573.90),
c("1996Q1", 8856.40), c("1996Q2", 8841.30))
dates <- a[,1]
# convert dates to years with fraction
year <- as.numeric(substring(dates,1,4)) + (as.numeric(substring(dates,6,6))-1)/4
values <- as.numeric(a[,2])
#time series starting with the first value and quarterly data
a<- ts(values,start = year[1], frequency = 4 )
print(a)
plot(a)