gpt4 book ai didi

r - 如何多次重复模拟?

转载 作者:行者123 更新时间:2023-12-01 01:46:55 25 4
gpt4 key购买 nike

我真的是 Rstudio 的新手,所以我希望有人能帮助我。
所以我有这个代码:

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)

当我运行它时,它会生成:
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

和这个:
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

基本上我想要做的是在代码中重复,这样当我点击运行时,无论我指定多少次,它都会生成这个。然后我希望它将它生成的 p 值分为两组,一组 p 值高于 0.05,另一组低于 0.05

正如我所说,我对此很陌生,所以如果有人能简单地向我解释一下,那将不胜感激。

最佳答案

要多次运行代码,请使用 replicate 。就像是

replicate(
100,
{
# Your code that creates the random dataset and runs ANOVA
}
)

关于r - 如何多次重复模拟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25758258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com