How to use Amelia package to get a best time series model in R

Viewed 173

I'm trying to handle the missing data from a data frame use multiple imputations, professor advice me to use Amelia package. And I can build the time series model, but when I try to use lapply function to repeatedly run the time series model in each dataset, I got an error on the function in lapply.

My data frame have three variables, date, pm25, pm10. I can built an AR model for pm25. And the imputation code is:

imp <- amelia(Exetertibble, m=50, ts = "date")

So I can get 50 imputations, and the time series model would like this:

model1 <- arima(imp$imputations$imp1$pm25, order = c(1,0,0))

Then I try to use lapply function:

extractcoefs <- lapply(imp$imputations, coef(model1))

There is an error, it said that the coef(model)is not a function or character or symbol.

My aim is to combine the 50 imputations and get the best result of coefficient of the time series model, I don't know how to write a correct function in there.

I also tried:

extractcoefs <- lapply(imp$imputations, coef(arima(order=c(1,0,0))))

and:

extractcoefs <- lapply(imp$imputations, arima(order=c(1,0,0)$coef))
1 Answers

No idea, what you are trying to do.

Look at this example for lapply:

x <- list(a = 1:10, beta = exp(-3:3), logic = c(TRUE,FALSE,FALSE,TRUE))
# compute the list mean for each list element
lapply(x, mean)

So you give lapply a list und apply a function on each of the list elements. In this case the function is mean(). So for this example you will get the mean for a, beta and logic.

You are using lapply on imp$imputations. You got imp$imputations from your call to the amelia() function. Which gives you an instance of S3 class "amelia". This instances includes several objects, one of these is a list imp, which has as list elements all the imputed datasets (in your case 50).

So using lapply(imp$imputations, coef(model1)) will apply the function in the second part on all imputed datasets. The only problem is, your second part isn't really a function. Also you can't apply coef on the imputed datasets. You must apply coef() on a model object, because it returns the model coefficients form the model.

I guess you want to do the following:

  1. Generate your m=50 imputed datasets
  2. Build a arima model for each dataset
  3. Get the coefficients for each of this model

You could just use a for loop through the m=50 datasets for this.

Take this as an example:

data(africa)
imp <- amelia(x = africa, cs = "country", ts = "year", logs = "gdp_pc", m = 5)

for (i in 1:length(imp$imputations)) 
{
  model <- arima(imp$imputations[[i]]$gdp_pc)
  coe <- coef(model)
  print(coe)
}

This would give you 50 results of coef. (for the different arima models build on the different m=50 imputed datasets)

Related