7
$\begingroup$

I'd like to simulate data for an interaction / moderation with a continuous exposure and outcome and binary moderator. For example, for the association between X and Y to be 0.1 when moderator = 0 and 0.2 when moderator = 1. This seems very simple but for some reason I'm struggling to do this in R. Any help would be much appreciated.

$\endgroup$
0

1 Answer 1

8
$\begingroup$

I see it as a question of how to generate data from a (linear?) model with interaction. See below for the R code where y is the response, x is the covariate and z is the binary moderator.

set.seed(12)

n <-  1000
# simulate a covariate
x <- rnorm(n)

# simualte a binary moderator
z <- sample(c(0,1),size = n, replace = T)
beta0 <- 1
beta1 <- 2
sigma0 <- 1

# mu
mu <- beta0 + beta1*z + 0.1*x*z + 0.1*x

y <- rnorm(n, mu, sigma0)
dd <- data.frame(y=y, x=x, z=z)
summary(lm(y~x*z, data = dd))
Call:
lm(formula = y ~ x * z, data = dd)

Residuals:
     Min       1Q   Median       3Q      Max 
-3.11036 -0.63836 -0.00177  0.64706  3.00070 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  0.98525    0.04612  21.364  < 2e-16 ***
x            0.15460    0.04985   3.101  0.00198 ** 
z            2.02830    0.06320  32.092  < 2e-16 ***
x:z          0.04727    0.06632   0.713  0.47615    
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.9966 on 996 degrees of freedom
Multiple R-squared:  0.5137,    Adjusted R-squared:  0.5123 
F-statistic: 350.7 on 3 and 996 DF,  p-value: < 2.2e-16
$\endgroup$
1
  • 3
    $\begingroup$ Here is a Python gist performing a similar simulation. $\endgroup$
    – Galen
    Oct 30, 2022 at 6:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.