如何在R中创建for循环?

时间:2010-11-12 18:43:26

标签: r

  

可能重复:
  how to start a for loop in R programming
  Creating a for loop in R

HI 这是场景

快速约会:你有信心你有15%的机会与任何给定的约会 当地速度约会活动的候选人。在活动中,您将恰好会见8名候选人。在与候选人交谈5分钟后,他/她会立即表明她是否想和你约会。

问题是......

通过模拟,找到你遇到的第三个候选人的第一个机会 给你一个约会。

我正在寻找能够回答这个问题的R代码(我认为这是一个for循环)

2 个答案:

答案 0 :(得分:18)

这是一个for循环示例:

for (i in 1:1e7) {
  cat("I LOVE HOMEWORK!!  ")
}

答案 1 :(得分:9)

这不是一个循环,但它更像是以R为中心:

N <- 1000 ## number of simulations to run
## Make this reproducible by seeding the random number generator
set.seed(1)
## read ?sample to see how this works
## Basically, sampling accept/not accept with 0.15/0.85 probability,
## N (1000) times for each of three Girls
df <- data.frame(Girl1 = sample(c(TRUE,FALSE), N, replace = TRUE,
                 prob = c(0.15,0.85)),
                 Girl2 = sample(c(TRUE,FALSE), N, replace = TRUE,
                 prob = c(0.15,0.85)),
                 Girl3 = sample(c(TRUE,FALSE), N, replace = TRUE,
                 prob = c(0.15,0.85)))
## Show some of the data
head(df)
## the row sums tell us how many accepts you'd get, 1, 2, or 3
outcomes <- rowSums(df)
## We want the rows with 1 acceptance **and** where Girl3 == TRUE
wanted <- with(df, which(outcomes == 1L & Girl3))
## This gives us the simulation probability
length(wanted) / N

对不起,这不是一个循环 - 但你可以尝试使用上面的循环来做这个指导。不能让我们做所有的工作。

相关问题