Reputation: 1159
I have a list with multiple elements, I need to apply ets function from forecast using two elements from each list.
Below is the list dat.list each list has time series called z
and a lam
## Create Dummy list
##Time series -> z, lambda - > lam
z <- ts(matrix(rnorm(30,10,10), 100, 3), start = c(1961, 1), frequency = 12)
lam <- 0.8
ap <- list(z=z,lam=lam)
z <- ts(matrix(rnorm(30,10,10), 100, 3), start = c(1971, 1), frequency = 12)
lam <- 0.5
zp <- list(z=z,lam=lam)
dat.list <- list(ap=ap,zp=zp)
Now I need take each time series z
and take lam
and apply it with ets
function from forecast
package. I used the following code.
library("forecast")
library("plyr")
ets.f <- function(x) {
forecast(ets(x$z, lambda = x$lam),h=12)$mean ## I need to apply lambda from list lam
}
ens.f <- function(x){
mm <- llply(x,ets.f)
tq <- matrix(unlist(mm), ncol = 12, byrow = TRUE)
tq
}
fore <- llply(dat.list, ens.f)
When I run the program i get the following error "Error in x$z : $ operator is invalid for atomic vectors"
.
I'm not sure how to apply individual elements of a list and apply it to a function. Any help would be greatly appreciated.
Thanks so much
Also, I also tried to separate z
and lam
in the list and was stuck on how to apply this. I'm apoen to using the code below as well. Thanks much appreciated.
ts.l <- lapply(dat.list,'[[','z')
lam.l <- lapply(dat.list,'[[','lam')
Upvotes: 1
Views: 586
Reputation: 887901
May be this helps:
lapply(dat.list, function(x) matrix(unlist(lapply(x$z,
function(y) forecast(ets(y, lambda=x$lam),
h=12)$mean)), ncol=12, byrow=TRUE))
Upvotes: 1