[R] decomposing decompose(), issue?

Peter L peteyofcanada at gmail.com
Fri Jun 15 05:04:41 CEST 2012


Hi

I'm just stepping through the decompose() function, in "stats".  Does
this contained line of code not work if you have a time series ending
"unevenly" (i.e., middle of the year), or am I missing something?

season <- na.omit(c(as.numeric(window(season, start(x) +
    c(1, 0), end(x))), as.numeric(window(season, start(x),
    start(x) + c(0, f)))))

The line seems to cut the first year of incomplete data, pare off NAs,
and stick the incomplete first year at the end.  It makes sense if I
have an data series that is a multiple of the frequency, but I am
perplexed otherwise.

Here's something to try.  I calculate the seasonal adjustment figures
in two ways here.  One is trying to replicate decompose(), and another
way which doesn't rely on the above line.
# I get identical results for:

x <- ts(c(6.3, 6.6, 7.5, 5.4, 6.7, 5.6, 6.9, 7.3, 5.3, 5.3, 4.8, 5.5,
5.4, 4.5, 7.7, 7.1, 6.1, 5.6, 7, 8.8, 7.8, 6, 5.8, 5.3, 6.2,
6.2, 6.3, 8.7, 6.8, 6.7, 9.3, 10.1, 8.2, 5.8, 5.2, 5.8), start=c(1987,
1), frequency=12)

# But different results for:

x <- ts(c(6.3, 6.6, 7.5, 5.4, 6.7, 5.6, 6.9, 7.3, 5.3, 5.3, 4.8, 5.5,
5.4, 4.5, 7.7, 7.1, 6.1, 5.6, 7, 8.8, 7.8, 6, 5.8, 5.3, 6.2,
6.2, 6.3, 8.7, 6.8, 6.7, 9.3, 10.1, 8.2, 5.8, 5.2, 5.8, 5.8,
7.5, 6.7, 6.4, 7.8, 6.5, 9.1, 10.7, 8.8, 5.5, 4.3, 4.3, 5, 6.2,
6.6, 5.3, 8.4), start=c(1987, 1), frequency=12)

# Here's what I run:

# This part takes the centered moving averages: trend
 l <- length(x)
 f <- frequency(x)
 filter <- c(0.5, rep(1, f - 1), 0.5)/f
 trend <- filter(x, filter)

# Assuming multiplicative
season <- x/trend

# This part confuses me!
season <- na.omit(c(as.numeric(window(season, start(x) +
   c(1, 0), end(x))), as.numeric(window(season, start(x),
     start(x) + c(0, f)))))

# Calculating the mean of seasonal factor for each month
periods <- l%/%f
index <- c(0, cumsum(rep(f, periods - 2)))
figure <- numeric(f)
for (i in 1L:f) figure[i] <- mean(season[index + i])

# Neutrality adjustment
figure <- figure/mean(figure)

# Here's an alternate method of calculating the monthly mean
figure_alt <- numeric(f)
for(i in 1L:f) figure_alt[i] <- mean((x/trend)[cycle(x)==i],na.rm=T)
figure_alt <- figure_alt/mean(figure_alt)

# For comparison
decompose(x,"multiplicative")$seasonal[1:12]
figure
figure_alt

Have I missed something fundamental, or is this a problem?

Peter



More information about the R-help mailing list