Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I repeat a simulation multiple times?

Tags:

r

I'm really new to Rstudio so I hope someone can help me. So I have this code:

x = 1:5
alpha = 1
beta = 1.5
betaD = 0.1
s = 1
sa = 0.2
sb = 0.2
N = 10

grp = factor(rep(c("Control", "Treatment"), c(N,N)))

for(i in 1:(2*N)) {
  ai = rnorm(1, 0, sa)
  bi = rnorm(1, 0, sb)
  intercept = alpha+ai
  slope = beta + bi + ifelse(grp[i]=="Treatment", betaD, 0.0)

  y = intercept+ slope*x + rnorm(length(x), 0, s)

  tmp = data.frame(subject=i, x=x, y=y, a=ai, b=bi, group=grp[i])
  if(i==1) dataset = tmp
  else dataset = rbind(dataset, tmp)
}

require(lme4)

fitAll= lmList(y~x|subject, data=dataset)
slopes = coef(fitAll)$x
boxplot(slopes~grp)
t.test(slopes~grp, var.equal=TRUE)

fit0 = lmer(y~ x +(x|subject), data=dataset, REML=FALSE)
fit1 = lmer(y~ group*x +(x|subject), data=dataset, REML=FALSE)
anova(fit0, fit1)

When I run this, it generates this:

Two Sample t-test

data:  slopes by grp
t = -2.2495, df = 18, p-value = 0.03723
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -0.66690111 -0.02277686
sample estimates:
  mean in group Control mean in group Treatment 
               1.362975                1.707814

and this:

Data: dataset
Models:
fit0: y ~ x + (x | subject)
fit1: y ~ group * x + (x | subject)
     Df    AIC    BIC  logLik deviance  Chisq Chi Df Pr(>Chisq)  
fit0  6 326.65 342.28 -157.32   314.65                           
fit1  8 324.34 345.18 -154.17   308.34 6.3072      2     0.0427 *
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Basically what I want to do is put a repeat in the code so that when I click run, it will generate this however many times I specify. Then I want it to sort the p-value it generates into two groups, one group where the p-value is above 0.05 and another where it is below 0.05

As I said I'm really new to this so if someone could explain it to me simply, that would be much appreciated.

like image 844
Joseph Avatar asked Dec 15 '22 20:12

Joseph


1 Answers

To run code several times, use replicate. Something like

replicate(
  100,
  {
     # Your code that creates the random dataset and runs ANOVA
  }
)
like image 162
Richie Cotton Avatar answered Jan 08 '23 06:01

Richie Cotton