How do I take the derivative of a line of best fit at a point without knowing the equation?

Viewed 53

Model:

mylogit <- glm(Result ~ kickLength, data = RegFg, family = "binomial") 

Probability plot:

plot.dat <- data.frame(prob = RegFg$NumMade/RegFg$NumKick, 
    kl = RegFg$kickLength, 
    fit = predict(mylogit, RegFg))
plot.dat$fit_prob <- exp(plot.dat$fit)/(1+exp(plot.dat$fit)) 
g1<-ggplot(plot.dat, aes(x=kl, y=prob)) +  
   geom_point() + geom_line(aes(x=kl, y=fit_prob)) 

Probability fit line (I think):

geom_line(aes(x=kl, y=fit_prob))

I am looking to find the derivative of probability with respect to kick length at each kick length.

1 Answers

If you want to do it without knowing the formula then that implies numeric differentiation. Now the input is missing from the question so let us use the example in the Note at the end so that it can actually be run -- next time please provide a complete runnable example. Then use numeric differentiation from the numDeriv package.

library(numDeriv)

prob <- function(x) predict(fm, list(x = x), type = "response")
grad1 <- grad(prob, x)  # find derivative at each x value

# check against formula in Ben Bolker's comment
grad2 <- coef(fm)["x"] * binomial()$mu.eta(predict(fm, list(x = x), type = "link"))
all.equal(grad1, grad2, check.attributes = FALSE)
## [1] TRUE

Note

set.seed(123)
success <- rep(0:1, each = 3)
x <- rnorm(6)
fm <- glm(success ~ x, family = binomial)
Related