B <- 10000
results <- replicate(B, {
hand <- sample(hands1, 2)
(hand[1] %in% aces & hand[2] %in% facecard) | (hand[2] %in% aces & hand[1] %in% facecard)
})
mean(results)
这段代码工作得很完美,并且达到了预期的效果。
这是一个蒙特卡罗模拟。我不明白他们在复制函数中放大括号{}的方式。我能理解这段代码的功能,但我不理解他们写代码的方式。
原因是我们有多个表达式
hand <- sample(hands1, 2)
是第一个表达式,第二个是
(hand[1] %in% aces & hand[2] %in% facecard) | (hand[2] %in% aces & hand[1] %in% facecard)
。如果只有一个表达式,我们不需要用{}
阻塞。这是一种一般情况,与replicate
无关,即如果我们使用for
循环与单个表达式,则不需要任何{}
for(i in 1:5)
print(i)
和类似的if/else
n <- 5
if(n == 5)
print(n)
只有在需要多个表达式
时才需要