> # fit model with hp

> lm.cars <- lm(mpg ~ hp + disp + drat + qsec, data = mtcars)

> # coefficient of hp for model

> coef(lm.cars)[2]

hp

-0.03610801

> # get terms

> pterms <- predict(lm.cars, type=”terms”)

> # calculate partial residuals

> partial.residuals <- apply(pterms,2,function(x)x+resid(lm.cars))

> # get “slope” of termplot

> # same as model coefficient

> lmout <- lm(partial.residuals[,1] ~ mtcars$hp)

> coef(lmout)[2]

mtcars$hp

-0.03610801

thanks for this post, it really helped a lot to see and work through the code to produce the termplot myself to understand what it shows.

However, when I applied this to my own data, I found that the slopes in the termplots were very different from the coefficients of my model. After trying to find out where my mistake was, I discovered that the slopes in the termplot do not reflect the coefficients. It matches pretty well in your example but this is just a coincidence because the variable wt as low values (i.e. up to 5 in comparison to disp which has values up to 400) and a high coefficient.

If you try the same procedure with e.g. hp instead of wt, the model coefficients and the slopes do not match (unfortunately, I cannot paste the plot here). What the termplot actually shows is the relative importance of a variable to the whole model. If we look at the model summary of a model with hp, we see that hp and disp have smaller coefficients than qsec but the slopes in the termplot are steeper. This is because if you multiply the mean of hp with its coefficient, it results in a larger negative value than when you multiply the mean of qsec with its coefficient (see below). Hence, hp has a greater influence on the predicted value than qsec, which is visible in the termplot but not in the coefficients.

I hope this helps other readers, which might stumble over the same problem with their own data.

Here is some code with hp instead of wt:

> summary(lm.cars)

Call: lm(formula = mpg ~ hp + disp + drat + qsec, data = mtcars)

Residuals:

Min 1Q Median 3Q Max

-4.9468 -1.8845 -0.5952 1.1165 6.6771

Coefficients:

Estimate Std. Error t value Pr(>|t|)

(Intercept) 24.241299 12.819746 1.891 0.0694 .

hp -0.036108 0.017464 -2.068 0.0484 *

disp -0.018879 0.009542 -1.978 0.0582 .

drat 2.555409 1.551713 1.647 0.1112

qsec -0.206682 0.467241 -0.442 0.6618

—

> mean(mtcars$hp)

[1] 146.6875

> mean(mtcars$qsec)

[1] 17.84875

> mean(mtcars$hp)*coef(lm.cars)[2]

hp

-5.296594 ## –> bigger effect even though the coefficient is smaller

> mean(mtcars$qsec)*coef(lm.cars)[5]

qsec

-3.68901