Created
October 18, 2024 06:01
-
-
Save JimGrange/5db0e04fe5f624ee8175a3d18fbc43e3 to your computer and use it in GitHub Desktop.
Simulating regression models for power estimates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(tidyverse) | |
# Set the effect size | |
eff_size <- 0.2 | |
# Function to simulate data, run regression, and check if individual predictors are significant | |
simulate_and_regress <- function(n) { | |
data <- tibble( | |
a = rnorm(n), | |
b = rnorm(n), | |
c = rnorm(n), | |
x = (eff_size * a) + (eff_size * b) + (eff_size * c) + rnorm(n) | |
) | |
model <- lm(x ~ a + b + c, data = data) | |
p_values <- summary(model)$coefficients[, "Pr(>|t|)"] | |
list( | |
a_significant = p_values["a"] < 0.05, | |
b_significant = p_values["b"] < 0.05, | |
c_significant = p_values["c"] < 0.05 | |
) | |
} | |
# Function to perform simulations for a given n and return power for each predictor | |
simulate_power <- function(n, reps = 1000) { | |
results <- replicate(reps, simulate_and_regress(n), simplify = FALSE) | |
results_df <- bind_rows(results) | |
power <- colMeans(results_df) | |
return(power) | |
} | |
# Vector of different sample sizes | |
sample_sizes <- seq(from = 50, to = 250, by = 10) | |
# Calculate power for each sample size and each predictor | |
set.seed(123) # For reproducibility | |
power_results <- map(sample_sizes, ~ as_tibble(simulate_power(.x))) | |
# Combine the sample sizes and power results into a data frame | |
power_df <- bind_cols(tibble(sample_size = sample_sizes), bind_rows(power_results)) | |
power_df |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment