Home > front end >  Efficiently run simulation in r for different parameter values
Efficiently run simulation in r for different parameter values

Time:01-05

I have a question about efficiently running simulations in R for different parameter settings. I have some function that calculates the sample size, and as an input, it takes two values. How can I run this function multiple times for different parameter settings each round.

This is my function:

samplesize <- function(var1, var2, cyc = 4){
  
  sd_sampsize <- sqrt(var1   (2*var2)/cyc)
  
  # Calculate the corresponding sample size plugging in the standard deviation
  pwrcalc <- pwr.t.test(d = 1/sd_sampsize, power = 0.8, sig.level = 0.05, 
                        type = "paired", alternative = "two.sided")
  
  # Extract the sample size from 'pwrcalc'
  finsampsize <- pwrcalc$n

  return(list(sd_sampsize, finsampsize))
}

So I want var1 and var2 to vary (say var1 to be 1, 2 and 3 and var2 to be 0.20, 0.50, 0.80). How can I do that without having to run the function several times for all the different combinations of var1 and var2? Thank you in advance!

CodePudding user response:

One option

var1=c(1,2,3)
var2=c(0.2,0.5,0.8)
cmb=expand.grid(var1,var2)

wut=function(x){
  v1=x[1]
  v2=x[2]
  list(v1,v2)
}

apply(cmb,1,wut)

note how the input x was separted into var1 and var2 before you do your thing in the function, if you want to keep your existing function as is - without changing the existing code.

  •  Tags:  
  • Related