如何在power.t.test

时间:2017-01-24 23:25:45

标签: r

我想使用每个delta值运行power.t.test来计算必要的样本数,然后将其保存到reps向量中的值以替换NA。我尝试创建一个for循环,但它只会更改保存代表的位置,并且每次都使用相同的delta值。有没有办法让for循环调用不同的delta值,即使它在另一个函数内部?

delta = c(.25,.5,.75,1,1.25,1.5,1.75,2)
reps = c(NA,NA,NA,NA,NA,NA,NA,NA)
reps[1] <- power.t.test(n = NULL,
                   delta = delta[1],
                   sd = pop_sd,
                   sig.level = 0.01,
                   power = 0.90,
                   type = 'paired',
                   alternative = 'two.sided'
                      )$n
ans <- data.frame(delta / pop_sd,reps)
ans

编辑:这是我的for循环,让我觉得我最接近。

for (x in delta){
  reps[1:8] <- power.t.test(n = NULL,  # make sure to fill in ALL of the ?
                       delta = delta[x],
                       sd = pop_sd,
                       sig.level = 0.01,
                       power = 0.90,
                       type = 'paired',
                       alternative = 'two.sided'
                          )$n
}

编辑2:我发现了我原来的错误。我需要使用for (i in 1:8)来调用deltareps中的索引编号。

for (i in 1:8){
  reps[i] <- power.t.test(n = NULL,  # make sure to fill in ALL of the ?
                       delta = delta[i],
                       sd = pop_sd,
                       sig.level = 0.01,
                       power = 0.90,
                       type = 'paired',
                       alternative = 'two.sided'
                          )$n
}

1 个答案:

答案 0 :(得分:1)

试试这个!

tmp_reps = lapply(1:length(delta), function(x){
           power.t.test(n = NULL,
           delta = delta[x],
           sd = pop_sd,
           sig.level = 0.01,
           power = 0.90,
           type = 'paired',
           alternative = 'two.sided')$n
})

reps <- unlist(tmp_reps)
ans <- data.frame(delta / pop_sd, reps)