简体   繁体   English

如何在自定义 function R 上进行循环?

[英]How to for-loop over a custom function R?

I wrote this function which returns the probability that the value 1 does not appear in a random sample when iterated 1000 times for varying sample sizes.我写了这个 function,它返回值 1 在针对不同样本大小迭代 1000 次时没有出现在随机样本中的概率。

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))
}

Now I want to use this function and another for-loop to calculate the probability for every sample size between 500 and 1500 and make a simple scatter plot of my results.现在我想使用这个 function 和另一个 for 循环来计算 500 到 1500 之间的每个样本大小的概率,并对我的结果进行简单的分散 plot。 Here is what I tried:这是我尝试过的:

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

Edit: when I run bday.function the output is number of TRUE values divided by the total (1000) TRUE/FALSE outcomes:编辑:当我运行 bday.function 时,output 是 TRUE 值的数量除以总(1000)TRUE/FALSE 结果:

bday.function(750)
[1] 0.122

I would like to replicate this for sample sizes between 500 and 1500 to generate a simple scatter plot我想对 500 到 1500 之间的样本大小进行复制,以生成简单的散点图 plot

Edit 2: Thanks to everybody for the help: Here's my final solution:编辑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")

在此处输入图像描述

As @JohnColeman pointed in his sage comment, your function can be slow.正如@JohnColeman在他的睿智评论中指出的那样,您的 function 可能会很慢。 Try these changes on your code for the printing output.尝试对您的代码进行这些更改以打印 output。 I have run only 60 sims as I need to complete other things:我只运行了 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)

Output: Output:

在此处输入图像描述

Are you looking for something like this?你在寻找这样的东西吗?

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")

在此处输入图像描述

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

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