Skip to content

Instantly share code, notes, and snippets.

@timcdlucas
Created May 14, 2021 10:43
Show Gist options
  • Save timcdlucas/bc8eaf878a81d4c3adeb7b750c3ef7fb to your computer and use it in GitHub Desktop.
Save timcdlucas/bc8eaf878a81d4c3adeb7b750c3ef7fb to your computer and use it in GitHub Desktop.
Deep interactions
library(ggplot2)
Xs <- 10
N <- 200
d <- data.frame(matrix(rnorm(Xs * N), nrow = N))
d$prod <- apply(d, 1, function(x) prod(x[1:5]))
d$y <- d$prod + rnorm(N, 0, 0.1)
ggplot(d, aes(y, prod)) +
geom_point()
ggplot(d, aes(y, X1)) +
geom_point()
ggplot(d, aes(y, X1 * X2)) +
geom_point()
testxs <- Xs
binary <- rep(list(0:1), testxs)
mods <- do.call(expand.grid, binary)
mods <- mods[rowSums(mods) > 1, ]
rsquared <- rep(NA, nrow(mods))
cand_xs <- names(d)[seq(testxs)]
for(i in seq_len(nrow(mods))){
covs <- cand_xs[as.logical(unlist(mods[i, ]))]
cov_string <- paste0(covs, collapse = ':')
print(cov_string)
form <- as.formula(paste0('y ~ ', cov_string))
m <- lm(form, data = d)
rsquared[i] <- summary(m)$adj.r.squared
}
plot(rsquared)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment