I dont understand what makes the different cases to work or not. I would have expected them to work all obviously.
- funs2 and funs4 only close over the last value of n for some reason : they behave as if n was always 5.
- funs3 captures each element of the sequence : it behaves as if n enumerated from 1 to 5, and mapped for each n to a different function, which will approximate the dataset differently (with increasing degree of freedom)
The script should be runnable directly in R with no dependance beside plyr.
Any clue ?
library(plyr)
f <- function (x) { sin(2*pi*x) }
fnoisy <- function (x) {f(x) + 0.3*rnorm(1)}
x10 <- runif(10)
y10 <- aaply(x10,1,fnoisy)
curve(f,0,1,col="blue", ylim=c(-1.5,1.5))
points(x10, y10, col="red")
vdm <- function(x,n) outer( x, seq(0,n-1), "^" )
fitted <- function (n) { function(xtrain,ytrain) { w <- qr.solve(vdm(xtrain,n), ytrain)
function (x) { vdm(x,n) %*% w} } }
funs2 <- lapply(seq_len(5), function(n) {fitted(n)}) #does not work
funs3 <- lapply(seq_len(5), function(n) {print(n);fitted(n)}) #works
funs4 <- lapply(seq_len(5), fitted ) #does not work
lapply(funs3, function(f) {ffitted <- f(x10,y10)
curve(ffitted,0,1,col="black", add=TRUE)})