Johan
Johan

Reputation: 828

Extracting slopes from earth model

I have some data for which I'ved used the earth model. I'm interested in the slopes of the different lines but looking at the model summary I don't get my expected values.

library(earth)
library(dplyr)
library(ggplot2)

d = structure(list(x = c(9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30), y = c(0.151534750704409, 
0.0348452707597105, -0.0913494247372798, -0.214465577974757, 
-0.365251164825619, -0.528214103496014, -0.614970081844732, 
-0.922572314358796, 
-1.15911158401926, -1.36432638285029, -1.51587576144429, -1.63708705686248, 
-1.7530889072188, -1.86142968143915, -1.98159646754281, -2.0994478459505, 
-2.23037530743309, -2.3421669680425, -2.40621060828366, -2.55432043723978, 
-2.73246980567199, -2.92496136528975)), .Names = c("x", "y"), row.names = 
c(NA, -22L), class = c("tbl_df", "tbl", "data.frame"))

mod = earth(y ~ x, data = d)

d$pred = predict(mod, newdata = d)

summary(mod, style = 'pmax')

this gives me this summary:

Call: earth(formula=y~x, data=d)

y =
  -1.314958
  - 0.06811314 * pmax(0,  x - 16) 
  +  0.1518165 * pmax(0, 19 -  x) 
  - 0.05124021 * pmax(0,  x - 19) 

Selected 4 of 4 terms, and 1 of 1 predictors
Termination condition: RSq changed by less than 0.001 at 4 terms
Importance: x
Number of terms at each degree of interaction: 1 3 (additive model)
GCV 0.004496406    RSS 0.04598597    GRSq 0.9953947    RSq 0.9976504

However when I look at my model the three different slopes all look negative:

ggplot(d, aes(x, y)) +
    geom_point() +
    geom_line(aes(x, pred)) + 
    theme(aspect.ratio = 1)  

slopes

How do I get the values for those 3 negative slopes?

Upvotes: 0

Views: 85

Answers (1)

Ryan
Ryan

Reputation: 934

mod$coefficients gives the coefficients. If the coefficients are on -x te slopes will be the negative of the coefficients. You can do mod$coefficients %>% {ifelse(grepl('-x', rownames(.)) , -., .)} to get the slopes (or just mentally reverse the signs for the portions with -x).

Upvotes: 1

Related Questions