Ndr
Ndr

Reputation: 574

Linear regression using a list of function

I've a dataset with X and Y value obtained from a calibration and I have to interpolate them with a predefined list of polynomial functions and choose the one with the best R2. The most silly function should be

try<-function(X,Y){
   f1<- x + I(x^2.0) - I(x^3.0)
   f2<- x + I(x^1.5) - I(x^3.0)
   ...
   f20<- I(x^2.0) - I(x^2.5) + I(x^0.5)

   r1<- lm(y~f1)
   r2<- lm(y~f2)
   ...
   r20<-lm(y~f20)

   v1<-summary(r1)$r.squared
   v2<-summary(r2)$r.squared
   ...
   v20<-summary(r20)$r.squared

   v<-c(v1,v2,...,v20)
   return(v)
  }

I'd like then to make this function shorter and smarter (especially from the definition of r1 to the end). I'd also like to give the user the possibility to choose a function among f1 to f20 (typing the desired row number of v) and see the output of the function print and plot on it.

Please, could you help me? Thank you.

@mso: the idea of using sapply is nice but unfortunately in this way I don't use a polynome for the regression: my x vector is transformed in the f1 vector according to the formula and then used for the regression. I obtain just one parameter instead of 3 (in this case).

Upvotes: 2

Views: 151

Answers (1)

rnso
rnso

Reputation: 24535

Create F as a list and proceed:

F = list(f1, f2, ...., f20)
r = sapply(F, function(x) lm(y~x))
v = sapply(r, function(x) summary(x)$r.squared)
return v

sapply will take each element of F and perform lm with y and put results in vector r. In next line, sapply will take every element of r and get summary and put the results in the vector v. Hopefully, it should work. You could also try lapply (instead of sapply) which is very similar.

Upvotes: 4

Related Questions