简体   繁体   中英

How can I calculate the slope from a linear regression analysis?

In R, I am trying to overlay an abline onto a plot, the result of linear regression. I want to create a scatter plot showing TrainRegRpt$train.data.Price (original price) on the x-axis, TrainRegress$fitted.values (the projected price that came from the lm model) on the y-axis and draw the line of best fit through the plotted points.

Here is some of my code:

TrainRegress <- lm(PriceBH.df$Price ~ ., data=PriceBH.df, subset = train.rows)
TrainRegRpt  <- data.frame(train.data$Price, TrainRegress$fitted.values, TrainRegress$residuals)
x <- as.vector(TrainRegRpt$TrainRegress.fitted.values)    # on the x-axis
y <- as.vector(TrainRegRpt$train.data.Price)     #on the y-axis
plot(TrainRegRpt$train.data.Price ~ TrainRegRpt$TrainRegress.fitted.values)
abline(x,y)

The scatter plot came out the same:

x <- as.vector(newdf$fv)
y <- as.vector(newdf$p)
p <-as.vector(TrainRegRpt$train.data.Price) # my y-axis in the scatter plot
fv <- as.vector(round(TrainRegRpt$TrainRegress.fitted.values,2) # my y-axis in the scatter plot
newdf<- dfrm <- data.frame(p,fv)
plot(newdf$p ~ newdf$fv)
abline(x,y)
summary(TrainRegress)

The following is the summary of TrainRegress: Coefficients obtained from the summary of TrainRegress:

Intercept  Estimate     
................30.318
CRIM.........0.245
CHAS......5.8368
RM..........8.4846

I extracted the y-intercept as follows:

y.interceptval <-summary(TrainRegress)$coefficients[1]

I will use y.interceptval in the abline(y.interceptval,***?slope***) but I need to know how to calculate the slope. How do I calculate the slope to pass to abline(y.interceptval, slope) ?

I have 5 textbooks here that are no help and my professor refuses to help me and I really want this to be perfect! Thank you!!!

plot(TrainRegRpt$train.data.Price ~ TrainRegRpt$TrainRegress.fitted.values)<br>
abline(x,y)

阴谋

It looks like you already calculated your slope. The slopes from a linear regression analysis using lm() are the coefficients. So, in this case, 30.318 is your Y-intercept.

This gives you a regression equation of:

Y = 30.318 + 0.245*(CRIM) + 5.8368*(CHAS) + 8.4846*(RM)

The numbers 0.245 , 5.8368 , and 8.4846 are the coefficients for each variable and they are also the individual slopes.

Also, one thing about your fitted vs reesiduals plot, it looks like you reversed the way abline() is supposed to be (ie instead of abline(x,y) it should be abline(y,x) .

Edit You used abline(x,y) but your plotted data are

plot(TrainRegRpt$train.data.Price ~ TrainRegRpt$TrainRegress.fitted.values)

( train.data.Price vs. Fitted Values not x vs y ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM