abenol
abenol

Reputation: 91

fill a matrix in a loop by function output

A function takes two sets of values from two vectors (alpha and beta). I need to place the values of the function output in a matrix with size alpha x beta. The function calculates power values. I appreciate your help. I need a matrix 5x5. I have attempted the following code so far:

alpha = c(0.01,0.05,0.10,0.20)
beta = c(0.50,0.60,0.70,0.80,0.90)
pwrmx <- matrix(data=NA, nrow=alpha, ncol=beta)
for (a in alpha){

  for (b in beta){

    pwr <- power.prop.test(n=NULL, p1=0.25, p2=0.4, sig.level = a, power = b)
    print(pwr$n)
    }

}

Upvotes: 2

Views: 133

Answers (2)

Mankind_2000
Mankind_2000

Reputation: 2218

you were almost there, refer the comments:

alpha = c(0.01,0.05,0.10,0.20)
beta = c(0.50,0.60,0.70,0.80,0.90)

# nrow and ncol depends on the length of alpha and beta
pwrmx <- matrix(data=NA, nrow=length(alpha), ncol=length(beta))

# iterate over the length so that you can use it to assign back at the correct index in matrix
for (i in 1:length(alpha)){

    for (j in 1:length(beta)){

        # as you are interested in the number n from the power analysis
        pwrmx[i,j] <- (power.prop.test(n=NULL, p1=0.25, p2=0.4, sig.level = alpha[i], power = beta[j]))$n

                             }

                          }

pwrmx
# .        [,1]      [,2]      [,3]      [,4]     [,5]
#[1,] 129.38048 155.72219 186.60552 226.29474 287.6656
#[2,]  74.90845  95.24355 119.70057 151.86886 202.8095
#[3,]  52.75810  70.01993  91.18885 119.50901 165.1130
#[4,]  32.02629  45.74482  63.12283  87.00637 126.4575

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389265

No need of loops, you can create a function to perform the calculation

func <- function(x, y) power.prop.test(n=NULL, p1=0.25, p2=0.4, sig.level = x, power = y)$n

and then use outer and apply the function (func) on each combination of alpha and beta

outer(alpha, beta, Vectorize(func))

#          [,1]      [,2]      [,3]      [,4]     [,5]
#[1,] 129.38048 155.72219 186.60552 226.29474 287.6656
#[2,]  74.90845  95.24355 119.70057 151.86886 202.8095
#[3,]  52.75810  70.01993  91.18885 119.50901 165.1130
#[4,]  32.02629  45.74482  63.12283  87.00637 126.4575

Upvotes: 0

Related Questions