I am trying to read in a time series and do a plot.ts(), however I am getting weird results. Perhaps I did something wrong. I tried including the start and end dates but the output is still wrong.
Any help appreciated. Thank you.
This is the code and output:
sales1 <- read.csv("TimeS.csv",header=TRUE)
sales1
salesT <- ts(sales1)
salesT
plot.ts(salesT)
output:
> sales1 <- read.csv("TimeS.csv",header=TRUE)
> sales1
year q1 q2 q3 q4
1 1991 4.8 4.1 6.0 6.5
2 1992 5.8 5.2 6.8 7.4
3 1993 6.0 5.6 7.5 7.8
4 1994 6.3 5.9 8.0 8.4
> salesT <- ts(sales1)
> salesT
Time Series:
Start = 1
End = 4
Frequency = 1
year q1 q2 q3 q4
1 1991 4.8 4.1 6.0 6.5
2 1992 5.8 5.2 6.8 7.4
3 1993 6.0 5.6 7.5 7.8
4 1994 6.3 5.9 8.0 8.4
> plot.ts(salesT)
It looks like I can't paste the plot. instead of 1 graph it has 5 separate
plots stacked onto each other.
The format of the original data is difficult to use directly for a time series. You could try this instead:
sales1 <- t(sales1[,-1])
sales1 <- as.vector(sales1)
my_ts <- ts(sales1, frequency = 4, start=c(1991,1))
plot.ts(my_ts)
Try this
salesT<-ts(unlist(t(sales1[,-1])),start=c(1991,1),freq=4)
Here I think you need to format it correctly try this:
salesT <- ts(sales1)
ts.plot(salesT, frequency = 4, start = c(1991, 1), end = c(1994, 4)))
This line is making the times into one of the series which is unlikely what you want:
> salesT <- ts(sales1)
We need to transpose the data frame in order that it reads across the rows rather than down and we use c
to turn the resulting matrix into a vector forming the data portion of the series. (continued after chart)
# create sales1
Lines <- "year q1 q2 q3 q4
1 1991 4.8 4.1 6.0 6.5
2 1992 5.8 5.2 6.8 7.4
3 1993 6.0 5.6 7.5 7.8
4 1994 6.3 5.9 8.0 8.4"
sales1 <- read.table(text = Lines, header = TRUE)
# convert to ts and plot
salesT <- ts(c(t(sales1[-1])), start = sales1[1, 1], freq = 4)
plot(salesT)
Regarding the comment, if the data looks like this then it is more straight forward and the lines below will produce the above plot. We have assumed that the data is sorted and starts at the bginning of a year so we do not need to use the second column:
Lines2 <- "year qtr sales
1 1991 q1 4.8
2 1991 q2 4.1
3 1991 q3 6.0
4 1991 q4 6.5
5 1992 q1 5.8
6 1992 q2 5.2
7 1992 q3 6.8
8 1992 q4 7.4
9 1993 q1 6.0
10 1993 q2 5.6
11 1993 q3 7.5
12 1993 q4 7.8
13 1994 q1 6.3
14 1994 q2 5.9
15 1994 q3 8.0
16 1994 q4 8.4"
sales2 <- read.table(text = Lines2, header = TRUE)
salesT2 <- ts(sales2$sales, start = sales2$year[1], freq = 4)
plot(salesT2)
Update fixed. Added response to comments.