Redd11
Redd11

Reputation: 1

Creating a loop that will allow you to populate an array with ‘power’ for a range of effect sizes and sample sizes (n)

I am trying to create a loop that will eventually allow me to plot the relationship sample size and power level for each effect size, using the Iris data set.I am trying to edit some existing code to do this but keep running into errors. I'd appreciate some help figuring this out. First I made vectors for effect size and sample size, then tried to make an array. This worked until I get to the loop where I got the error message

`Error in pwr.t.test(n = n[i], e = e[j], sig.level = 0.05, power = NULL,  : unused argument (e = e[j])`

    `#Vector effect size
    e <- seq(.2,1,.1);e
    el<-length(e)
    
    #Vector sample size 
    n<- seq(10,50,1);n
    nl <- length(n)
    
    
    #Loop populate an array with ‘power’ for a range of effect sizes and sample sizes (n)
    Irispower <- array(numeric(el*nl), dim=c(el,nl));Irispower  # sets up an array for effect*sample size
    for (i in 1:nl){ #nl is sample size
      for (j in 1:el){ #el is effect size
        result <- pwr.t.test(n = n[i], e = e[j],
                             sig.level = .05, power = NULL,
                             type = "two.sample", alternative="two.sided")
        Irispower[j,i] <- ceiling(result$power) #asking for the n of the result to be put 
        #into power according to sample/effect size
      }
    }`

Upvotes: 0

Views: 36

Answers (1)

Edward
Edward

Reputation: 19339

library(pwr)

# Vector effect size
d <- seq(.2, 1, 0.1)
dl <- length(d)

# Vector sample size 
n <- seq(10, 14, 1)
nl <- length(n)

Irispower <- array(numeric(dl*nl), dim=c(dl,nl))

for (i in 1:nl)
  for (j in 1:dl)
    Irispower[j,i] <- pwr.t.test(n = n[i], d = d[j])$power

Irispower

            [,1]       [,2]       [,3]       [,4]       [,5]
 [1,] 0.07082135 0.07317951 0.07554086 0.07790573 0.08027433
 [2,] 0.09742459 0.10285147 0.10829259 0.11374773 0.11921637
 [3,] 0.13545156 0.14529564 0.15516183 0.16504593 0.17494341
 [4,] 0.18509566 0.20062714 0.21614307 0.23162784 0.24706609
 [5,] 0.24593206 0.26811887 0.29012879 0.31192504 0.33347366
 [6,] 0.31667051 0.34592375 0.37461680 0.40268718 0.43008155
 [7,] 0.39506921 0.43103846 0.46575929 0.49915695 0.53117735
 [8,] 0.47805041 0.51954656 0.55877679 0.59569850 0.63030503
 [9,] 0.56200665 0.60709780 0.64864255 0.68671060 0.72141975

Can also use outer instead of the double loop:

POWER <- function(n, d)
  pwr.t.test(n,d)$power

Irispower2 <- t(outer(n, d, FUN=POWER))

identical(Irispower, Irispower2)
# [1] TRUE

Upvotes: 0

Related Questions