# EXGM (1, 1): Exponential grey model
# Input data x0
x0 <- c(2028,2066,2080,2112,2170,2275,2356,2428)
# Calculate accumulated generating operation (AGO)
x1 <- cumsum(x0)
# n is the length of sequence x0
n <- length(x0)
# Create matrix y
y <- matrix(c(x0),ncol=1)
y <- t(t(x0[2:n]))
b <- numeric(n)
for (i in 1:n){
b[i] <- -0.5*(x1[i+1] + x1[i])
}
b1 <- b[1:n-1]
# Create matrix B2
mat1 <- matrix(c(b1),ncol=1)
mat2 <- matrix(1,nrow=n-1,ncol=1)
f <- numeric(n)
for (i in 1:n){
f[i] <- ( exp(1) - 1) * exp(-i)
}
f1 <- f[2:n]
mat3 <- matrix(c(f1),ncol=1)
B2 <- cbind(mat1, mat2, mat3)
# Parameters estimation (a, b and c) by ordinary least squares method (OLS)
rcap <- (solve (t(B2) %*% B2)) %*% t(B2) %*% y
a <- rcap[1,1]
b <- rcap[2,1]
c <- rcap[3,1]
scale_with <- function(k)
{
( x1[1] - (b/a) - ( ( c/(a-1) )*exp(-1) ) ) * exp(a*(1-k)) + (b/a) + ( c/(a-1) )*exp(-k)
}
forecast1 <- scale_with(1:n)
x1cap <- c(forecast1)
x0cap1 <- numeric(n)
for (i in 1:n){
x0cap1[i] <- x1cap[i+1] - x1cap[i]
}
x0cap <- c(x0[1],x0cap1[1:n-1])
# Fitted values
x0cap
# A is the number of forecast values
A <- 4
x1cap4 <- scale_with(1 : n+A )
t4 <- length(x1cap4)
x0cap4 <- numeric(t4-1)
for (i in 1:t4-1) {
x0cap4[i] <- x1cap4[i+1] - x1cap4[i]
}
x0cap4 <- c(x0[1],x0cap4[1:t4-1])
x0cap5 <- tail(x0cap4,A)
# Predicted values
x0cap5
x0cap2 <- c(x0cap,x0cap5)
# Fitted and predicted values
x0cap2
Run the code above in your browser using DataLab