Skip to content

Instantly share code, notes, and snippets.

@soodoku
Created September 22, 2024 00:20
Show Gist options
  • Save soodoku/d77249a2db390be95ac80feb8000a07e to your computer and use it in GitHub Desktop.
Save soodoku/d77249a2db390be95ac80feb8000a07e to your computer and use it in GitHub Desktop.
Attenuation Bias Simulation
# Set seed for reproducibility
set.seed(123)
# Number of observations
n <- 1000
# Simulate a perfectly measured outcome (Y_perfect)
# Treatment effect
treatment_effect <- 5
base_noise <- rnorm(n, mean = 0, sd = 1) # Base noise for the perfect outcome
# Simulate the treatment assignment (randomized)
treatment <- rbinom(n, 1, 0.5) # Random assignment to treatment (0 or 1)
# Perfectly measured outcome
Y_perfect <- treatment_effect * treatment + base_noise
# Simulate the noisy outcome
# Assume half respond sincerely and half respond randomly
random_respondents <- sample(1:n, size = n / 2) # Randomly select half to respond randomly
Y_noisy <- Y_perfect # Start with Y_perfect for everyone
Y_noisy[random_respondents] <- rnorm(n / 2, mean = 0, sd = 5) # Replace with random noise for half
# Perform linear regression on both the perfectly measured and noisy outcomes
model_perfect <- lm(Y_perfect ~ treatment)
model_noisy <- lm(Y_noisy ~ treatment)
# Summarize the results
summary(model_perfect)
summary(model_noisy)
# Compare the estimated treatment effects
cat("Treatment effect on perfectly measured outcome:\n")
cat("Estimate:", coef(model_perfect)[2], "\n\n")
cat("Treatment effect on noisy outcome (half random responses):\n")
cat("Estimate:", coef(model_noisy)[2], "\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment