Skip to content

Instantly share code, notes, and snippets.

@leeper
Created April 15, 2017 16:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leeper/d69f154b38832863e84cd1034ebbc44b to your computer and use it in GitHub Desktop.
Save leeper/d69f154b38832863e84cd1034ebbc44b to your computer and use it in GitHub Desktop.
library("rtruncnorm")
library("prediction")
library("margins")
set.seed(14850)
n <- 300
error <- 4
ex <- data.frame(
d = rbinom(n,1,.5),
x = rnorm(n),
e = rnorm(n,0,error))
ex$y <- with(ex, 1 + d + x + e)
mod <- lm(y ~ d * x, data = ex)
cplot(mod, x = "x", dx = "d", what = "effect")
summary(mod)
summary(margins(mod, at = list(x = seq_range(x, 5))))
exsplit5 <- split(ex, cut(ex$x, 5))
lapply(exsplit5, function(dat) {
summary(margins(mod, data = dat))
})
exsplit3 <- split(ex, cut(ex$x, 3))
lapply(exsplit3, function(dat) {
summary(margins(mod, data = dat))
})
ex$xbin5 <- as.factor(as.integer(cut(ex$x, 5)))
mod5 <- lm(y ~ d * xbin5, data = ex)
ex$xbin3 <- as.factor(as.integer(cut(ex$x, 3)))
mod3 <- lm(y ~ d * xbin3, data = ex)
summary(margins(mod5, at = list(xbin5 = levels(ex$xbin5))))
summary(margins(mod3, at = list(xbin3 = levels(ex$xbin3))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment