简体   繁体   English

在 r 中针对不同的参数值高效地运行仿真

[英]Efficiently run simulation in r for different parameter values

I have a question about efficiently running simulations in R for different parameter settings.我有一个关于在 R 中针对不同参数设置有效运行模拟的问题。 I have some function that calculates the sample size, and as an input, it takes two values.我有一些 function 计算样本量,作为输入,它需要两个值。 How can I run this function multiple times for different parameter settings each round.如何为每轮不同的参数设置多次运行此 function。

This is my function:这是我的 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).所以我希望var1var2变化(比如var1为 1、2 和 3, var2为 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 ?我怎样才能做到这一点,而不必为var1var2的所有不同组合多次运行 function ? Thank you in advance!先感谢您!

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.请注意输入 x 在您在 function 中执行操作之前是如何分隔为 var1 和 var2 的,如果您想保持现有的 function 原样 - 而不更改现有代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM