Predict() - Maybe I'm not understanding it

前端 未结 4 1718
梦毁少年i
梦毁少年i 2020-11-22 08:19

I posted earlier today about an error I was getting with using the predict function. I was able to get that corrected, and thought I was on the right path.

4条回答
  •  一向
    一向 (楼主)
    2020-11-22 08:41

    First, you want to use

    model <- lm(Total ~ Coupon, data=df)
    

    not model <-lm(df$Total ~ df$Coupon, data=df).

    Second, by saying lm(Total ~ Coupon), you are fitting a model that uses Total as the response variable, with Coupon as the predictor. That is, your model is of the form Total = a + b*Coupon, with a and b the coefficients to be estimated. Note that the response goes on the left side of the ~, and the predictor(s) on the right.

    Because of this, when you ask R to give you predicted values for the model, you have to provide a set of new predictor values, ie new values of Coupon, not Total.

    Third, judging by your specification of newdata, it looks like you're actually after a model to fit Coupon as a function of Total, not the other way around. To do this:

    model <- lm(Coupon ~ Total, data=df)
    new.df <- data.frame(Total=c(79037022, 83100656, 104299800))
    predict(model, new.df)
    

提交回复
热议问题