如何在R中创建for循环?

Joe*_*Joe 2 r

可能的重复:
如何在R编程中启动for循环在R中
创建for循环

HI这是场景

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

问题是...

通过模拟,找到您遇到的第三个候选人是第一个为您提供约会的机会.

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

JD *_*ong 18

这是一个for循环示例:

for (i in 1:1e7) {
  cat("I LOVE HOMEWORK!!  ")
}
Run Code Online (Sandbox Code Playgroud)


Rei*_*son 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
Run Code Online (Sandbox Code Playgroud)

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