broccoli
broccoli

Reputation: 4836

R fitting a polynomial on data

I have some data synthetically generated from a function which is shown below.

fn <- function(w1,w2){
  f= -(0.1 + 1.3*w1 + 0.4*w2 - 1.8*w1*w1 - 1.8*w2*w2)
  return(f)
}

Next I create a data frame with the values as shown below

x = data.frame(
  yval = fn(seq(0.1,0.9,by=0.01),seq(1.1,0.3,by=-0.01)),
  x1 = seq(0.1,0.9,by=0.01),
  x2 = seq(1.1,0.3,by=-0.01)
)

I want to see if I can recreate the coefficients of the polynomial in fn by using a polynomial fit which I attempt as shown below

fit = lm(yval ~ x1 + x2 + I(x1^2) + I(x2^2),data=x)
coef(fit)

However when I run the above code, I get the following

(Intercept)          x1          x2     I(x1^2)     I(x2^2) 
      2.012      -5.220          NA       3.600          NA 

It appears that the term x2 was never "detected". Would anybody know what I could be doing wrong? I know that if I create synthetic linear data and try to re-create the coefficients using lm, I would get back the coefficients fairly accurately. Thanks in advance.

Upvotes: 1

Views: 321

Answers (1)

Hong Ooi
Hong Ooi

Reputation: 57686

If you're fitting to a grid of 2 predictors, you want expand.grid.

x <- expand.grid(x1=seq(0.1, 0.9, by=0.01), x2=seq(1.1, 0.3, by=-0.01))
x$yval <- with(x, fn(x1, x2))

fit = lm(yval ~ x1 + x2 + I(x1^2) + I(x2^2),data=x)
coef(fit)
(Intercept)          x1          x2     I(x1^2)     I(x2^2) 
       -0.1        -1.3        -0.4         1.8         1.8 

Upvotes: 5

Related Questions