如何对自定义函数 R 进行循环?

How to for-loop over a custom function R?

我写了这个函数,它 returns 当针对不同的样本大小迭代 1000 次时,值 1 不出现在随机样本中的概率。

bday.function <- function(sample.size){
  x <- vector()
  for (i in 1:1000){
  x[i] <- !any(data.frame(table(sample(1:365, sample.size, replace=TRUE)))$Var1 == 1)
}
  return(mean(x))
}

现在我想使用这个函数和另一个 for 循环来计算 500 到 1500 之间的每个样本量的概率,并绘制我的结果的简单散点图。这是我尝试过的:

z <- vector()
for (i in 500:1500) {
  z[i] <- bday.function(i)
  return(plot(z))
}

编辑:当我 运行 bday.function 时,输出是 TRUE 值的数量除以总数 (1000) TRUE/FALSE 结果:

bday.function(750)
[1] 0.122

我想对 500 到 1500 之间的样本量进行复制以生成一个简单的散点图

编辑2:感谢大家的帮助!这是我的最终解决方案:

x <- vector(length = 1000)

for (i in 1:1000){
  x[i] <- !any(sample(1:365, 500, replace=TRUE) == 1) 
}

x
bday.function <- function(sample.size){
  x <- vector(length= 1000)
  for (i in 1:1000){
  x[i] <- !any(sample(1:365, sample.size, replace=TRUE) == 1) 
}
  return(mean(x))
}
bday.function(750)
z <- vector(length = 1000)
tmp.index <- 500:1500
for (i in seq_along(tmp.index)) {
  z[i] <- bday.function(tmp.index[i])
}
#Plot
plot(tmp.index, z, xlab = "sample size", ylab = "Probability of no birthdays")

正如 @JohnColeman 在他的明智评论中指出的那样,您的功能可能很慢。尝试对打印输出代码进行这些更改。我只有 运行 60 个模拟人生,因为我需要完成其他事情:

#Function
bday.function <- function(sample.size){
  x <- vector()
  for (i in 1:1000){
    x[i] <- !any(data.frame(table(sample(1:365, sample.size, replace=TRUE)))$Var1 == 1)
  }
  return(mean(x))
}
#Loop
z <- vector()
vec <- 500:1500
for (i in seq_along(vec)) {
  z[i] <- bday.function(vec[i])
}
#Plot
plot(z)

输出:

您在找这样的东西吗?

bday.function <- function(sample.size) {
  
  mean(sapply(seq(1000), function(x)
    +!any(sample(365, sample.size, replace = TRUE) == 1)))
}

x <- 500:1500
y <- sapply(x, bday.function)
plot(x, y, xlab = "sample size", ylab = "Probability of no birthdays")