R: Numeric 'Envir' Arg Not of Length One in Predict()

R: numeric 'envir' arg not of length one in predict()

There are several problems here:

  1. The newdata argument of predict() needs a predictor variable. You should thus pass it values for Coupon, instead of Total, which is the response variable in your model.

  2. The predictor variable needs to be passed in as a named column in a data frame, so that
    predict() knows what the numbers its been handed represent. (The need for this becomes clear when you consider more complicated models, having more than one predictor variable).

  3. For this to work, your original call should pass df in through the data argument, rather than using it directly in your formula. (This way, the name of the column in newdata will be able to match the name on the RHS of the formula).

With those changes incorporated, this will work:

model <- lm(Total ~ Coupon, data=df)
new <- data.frame(Coupon = df$Coupon)
predict(model, newdata = new, interval="confidence")

Understanding the Linear Model in R

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."

in R, predict yields wrong length

You can simplify with:

library(ISLR)

Hitters <- na.omit(Hitters) # remove NA

set.seed(1)
train <- sample(1:nrow(Hitters), nrow(Hitters)/2) # random sampling
test <- (1:nrow(Hitters))[-train] # your definition of test was incorrect

lm.fit <- lm(Salary ~ ., data = Hitters, subset = train)
lm.pred <- predict(lm.fit, newdata = Hitters[test,])

dim(Hitters[test,]) # output 132*20
length(lm.pred) # output 132


Related Topics



Leave a reply



Submit