简体   繁体   English

如何在循环中执行循环并将其保存在R中的表中

[英]How to do a loop in a loop and save it in a table in r

The problem is: If a teacher makes a bet with his class of 35 people "how many people have the same birthday?". 问题是:如果一位老师在他的35人班上打赌“多少人有相同的生日?”。 If he loses the bet he pays $2, if he wins the bet, he gets $1. 如果他输掉了赌注,则支付2美元;如果赢了赌注,则得到1美元。 He did this bet 1137 times. 他下注1137次。 So, I did a loop to represent this. 因此,我做了一个循环来表示这一点。 Now, I want to repeat this test 1000 times and save it in a vector or table, so I can then run an inferential test on it. 现在,我想重复此测试1000次并将其保存在向量或表中,以便随后对它进行推论测试。 How do I repeat the loop? 如何重复循环?

```{r}

exact=c(seq(1:365), seq(1:365), seq(1:365), seq(1:366))  
bucket=numeric()  
smithbucks=0  
for(i in 1:1137){  
  class=sample(exact, size = 35, replace = TRUE)  
hmmm=sum(duplicated(class))  
if (hmmm > 0) smithbucks = smithbucks +1  
else smithbucks = smithbucks -2}  

```

Lots of ways to do it. 有很多方法可以做到这一点。 One simple way is to put it inside a sapply loop as such: 一种简单的方法是将其放入一个sapply循环中,如下所示:

results <- sapply(1:1000, function(i) {
    exact=c(seq(1:365), seq(1:365), seq(1:365), seq(1:366))  
    smithbucks=0  
    for(i in 1:1137){  
      class=sample(exact, size = 35, replace = TRUE)  
    hmmm=sum(duplicated(class))  
    if (hmmm > 0) smithbucks = smithbucks +1  
    else smithbucks = smithbucks -2}
    return(smithbucks)
})

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

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