strengejacke / ggeffects

Estimated Marginal Means and Marginal Effects from Regression Models for ggplot2
https://strengejacke.github.io/ggeffects
Other
544 stars 35 forks source link

r ggeffect random sample linear spline #504

Closed ndsubison2178 closed 5 months ago

ndsubison2178 commented 5 months ago

Assuming this is my dataset

set.seed(666)
n <- 200
d <- data.frame(
  x = scales::rescale(rchisq(n, 6), c(0, 20))
)
d$interval <- findInterval(d$x, c(5, 10), rightmost.closed = TRUE) + 1
d$slope <- c(2, -3, 0)[d$interval]
d$intercept <- c(0, 25, -5)[d$interval]
d$y <- with(d, intercept + slope * x + rnorm(n, 0, 1))

This is what it looks like like

library(ggplot2)
fig <- ggplot(d, aes(x=x, y=y)) + 
  geom_point(aes(shape=as.character(slope))) +
  scale_shape_discrete(name="Slope") +
  theme_bw()
fig

image

If I fit a model with a linear spline term like this.

library(lspline) m1 <- lm(y ~ lspline(x, c(5, 10)), data=d)

How can I apply the ggpredict function with the following requirements 1) estimate marginal effects for all values below the first knot (x<5), 2) for values above the first knot (x>5), select a random sample of 20 observations including the maximum x value and estimate the marginal effects for these random 20 x values above the 1st knot ?

Thanks.

ndsubison2178 commented 5 months ago

Not important