Reputation: 27
I have a time series from 1951 to 2012. Part below
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1951 15.50 18.74 22.75 25.90 25.43 27.61
1952 27.60 27.72 27.63 24.38 20.34 17.74 17.90 20.57 23.13 25.60 26.41 26.98
1953 25.80 26.19 24.99 23.23 19.59 15.78 14.85 18.97 20.44 25.78 26.65 27.00
1954 26.25 26.97 25.33 23.16 20.47 15.47 15.64 18.33 22.71 26.71 25.77 25.94
I also got vector of the means of all the Jans, Feb, etc, below
[1] 27.80410 27.24500 26.14211 23.76737 20.19474 16.87368 16.71846 19.28359 22.74385
[10] 25.22513 26.50128 27.21410
I need to subtract the mean of January from all the Januaries, the same for February etc.
But if I do a simple subtract I will get January subtracting from Julys etc
The time series is a time series and the mean is a vector.
Can you tell me how to get past this and the whole process is part of a loop.
Upvotes: 1
Views: 89
Reputation: 887158
We need to use the cycle
function to index the time series
ts1-v1[cycle(ts1)]
# Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
#1951 -1.21 -0.54 0.01 0.67 -1.07 0.41
#1952 -0.20 0.48 1.49 0.62 0.15 0.87 1.19 1.29 0.39 0.37 -0.09 -0.22
#1953 -2.00 -1.05 -1.15 -0.53 -0.60 -1.09 -1.86 -0.31 -2.30 0.55 0.15 -0.20
#1954 -1.55 -0.27 -0.81 -0.60 0.28 -1.40 -1.07 -0.95 -0.03 1.48 -0.73 -1.26
ts1 <- structure(c(15.5, 18.74, 22.75, 25.9, 25.43, 27.61, 27.6, 27.72,
27.63, 24.38, 20.34, 17.74, 17.9, 20.57, 23.13, 25.6, 26.41,
26.98, 25.8, 26.19, 24.99, 23.23, 19.59, 15.78, 14.85, 18.97,
20.44, 25.78, 26.65, 27, 26.25, 26.97, 25.33, 23.16, 20.47, 15.47,
15.64, 18.33, 22.71, 26.71, 25.77, 25.94), .Tsp = c(1951.5, 1954.91666666667,
12), class = "ts")
v1 <- c(27.80, 27.24, 26.14, 23.76, 20.19, 16.87, 16.71, 19.28, 22.74, 25.23,
26.5, 27.2)
Upvotes: 1