2
votes

The R language has always been a bit of a mystery to my -- so although I know what linear regression is -- some of the following syntax escapes me.

So say I have the following:

x <- c(1, 2, 3, 4)
y <- c(2.1, 3.8, 6.5, 7.78)
lm1 <- lm(y~x)

My understanding is the lm1 contains the linear model which when I print it out confirms that (I think):

> lm1

Call:
lm(formula = y ~ x)

Coefficients:
(Intercept)            x  
      0.110        1.974  

Now when I want to run this in production mode I do the following (I want to predict the values of x=10 and x=20:

test <- c(10,20)
predict(lm1, test)

I get the following:

Error in eval(predvars, data, env) : numeric 'envir' arg not of length one

Any help appreciated.

Data

> dput(x)
c(1, 2, 3, 4)
> dput(y)
c(2.1, 3.8, 6.5, 7.78)
> dput(test)
c(10, 20)
1
test<- data.frame(x=c(10,20)); predict(lm1, newdata=test) - C8H10N4O2

1 Answers

7
votes

predict() needs the newdata= parameter to be a data.frame. It uses the names of the columns in the data.frame to match up to the variables in your formula. This is especially necessary when your model has more than one predictor.

You can do

predict(lm1, data.frame(x=test))

Also it would be better to fit your model using a data.frame as well.

dd<-data.frame(
    x = c(1, 2, 3, 4),
    y = c(2.1, 3.8, 6.5, 7.78)
)
lm1 <- lm(y~x, dd)
predict(lm1, data.frame(x=c(10,20)))

This generally leads to fewer "surprises."