[R] assigning a function within a loop

Hanck, Christoph Christoph.Hanck at vwl.uni-due.de
Wed Oct 29 13:16:53 CET 2014


Hi,

I am trying to run several polynomial regressions on simulated data and produce fitted values with the pol1, pol2 functions (predict produces not so nice plots, see http://www.r-bloggers.com/polynomial-regression-techniques/). Below's a simplified version of what I try to achieve. It seems that while assigning within a loop does work, my assignment gets overwritten.

Any ideas - I suspect it is a basic mistake, my first post here...

Best,
Christoph

rm(list=ls())

# data generation
N=10
u = rnorm(N,0,.25)
x = sort(runif(N))
y = sin(2*pi*x)+u

# number of polynomials (just 2 for simplicity here)
degree = 2

plot(x,y)
for(i in 1:degree)
{
  nam <- paste("fit",i,sep = "")
  assign(nam, lm(y~poly(x,i,raw=TRUE))) # works nicely and I can access fit1, fit2 later

  nam2 <- paste("pol",i,sep = "")
  assign(nam2, function(x) matrix(x^rep(0:i,each=length(x)),ncol=i+1)%*%get(paste("fit",i,sep = ""))$coefficient[1:(i+1)])

  if(i==1) print(pol1(x)) # something different than pol2(x)
  #curve(get(paste("pol",i,sep = "")), col=20+i, lwd=2, add = TRUE) # the ultimate goal
}

print(pol1(x)) # produces the same result as pol2(x), although it did not in the loop
print(pol2(x))

	[[alternative HTML version deleted]]



More information about the R-help mailing list