I'm very confused by what's going on in this example.
I'm trying to write a function factory and pass it a list of parameters to create a list of functions. I've had luck with this method for simple functions. Now I'm trying to do a more complex problem that uses a list of parameters. I was not able to get it to work with lapply, but I'm open to that approach. I tried a loop instead and things are behaving strangely.
library(TTR)
data(ttrc)
#last 100 closing prices for testing
ttrc <- tail(ttrc['Close'], 100)
#Function Factory for creating moving average functions
MAFactory <- function(fun, n) function(x){
setNames(get(fun)(x = x, n = n), paste(fun, n, sep = "_"))
}
#parameters to use with the funciton factory
grid <- expand.grid(fncts = c("SMA", "EMA", "DEMA"),
ns = c(10, 20, 30),
stringsAsFactors = FALSE)
MAfuns <- vector("list", nrow(grid))
#loop over the grid to apply the function factory
for (i in 1:nrow(grid)) {
#print statements for debugging
print(i)
MAfuns[[i]] <- MAFactory(grid[i, 1], grid[i, 2])
print(paste(grid[i,], collapse = ''))
}
#test cases
sma10 <- MAFactory("SMA", 10)
sma10Simple <- SMA(x = ttrc, n = 10)
(sma10Simple == sma10(ttrc))
(MAfuns[[1]](ttrc) == sma10(ttrc))
(MAfuns[[1]](ttrc) == sma10Simple)
#cause of failure
tmpE <- environment(MAfuns[[1]])
mget(envir = tmpE, x = ls(envir = tmpE))
#all MAfuns use last parameters from grid???
#but it works outside the loop when i = 1?!
MAfuns[[1]] <- MAFactory(grid[1, 1], grid[1, 2])
(MAfuns[[1]](ttrc) == sma10(ttrc))
I think the issue has something to do with promise evaluation, based on this question. But the fix, calling the argument in the function factory, does not work for me. If for some reason this can't be done inside a loop, how could I rewrite it with lapply?