有没有办法在 R 中为不同的样本大小复制一个函数?

Is there a way to replicate a function for different sample sizes in R?

我想针对不同的样本量模拟此函数。澄清一下,我不希望模拟被 运行 更改的次数 (n),而是我想在 ok 函数中针对不同大小复制此模拟(ok 函数中的当前大小是2,我想为尺寸 2 到 10 复制此功能)。

非常感谢。如果有任何部分需要澄清,请告诉我。

simulate_f <- function(n){

  n <- 2000
  n.run <- 0
  
  for (i in 1:n){
  
 ok <- sample(1:4, size=2 ,replace=TRUE)

 if(var(ok)==0){
   n.run <- n.run + 1
   
 }
 
}

n.run/n

}

simulate_f()

如果 n 是常量,我们可能不需要它作为参数。相反,使用 size 作为函数

中用作变量组件的输入
simulate_f <- function(size){

  n <- 1000
  n.run <- 0
  
  for (i in 1:n){
  
 ok <- sample(1:4, size=size ,replace=TRUE)

 if(var(ok)==0){
   n.run <- n.run + 1
   
 }
 
}

n.run/n

}

sapply(2:10, simulate_f)