R 使用蒙特卡洛随机排列40名男性和10名女性
正在进行一些Monte Calo模拟: 排队等候的人有40名男子和10名女子,按随机顺序排列。需要估计队列中没有两个女性相邻的概率R 使用蒙特卡洛随机排列40名男性和10名女性,r,montecarlo,R,Montecarlo,正在进行一些Monte Calo模拟: 排队等候的人有40名男子和10名女子,按随机顺序排列。需要估计队列中没有两个女性相邻的概率 nrep = 100000 count = 0 for (i in 1:nrep) { 现在对于这个示例,有没有一种方法可以让我写“40m”,然后程序将其读取为40个不同的对象 关于这个问题,我可以问一下,在这10个总数中,是否有女性在旁边 这个怎么样: library(zoo) library(tidyverse) isWoman <- c(rep(F
nrep = 100000
count = 0
for (i in 1:nrep) {
现在对于这个示例,有没有一种方法可以让我写“40m”,然后程序将其读取为40个不同的对象
关于这个问题,我可以问一下,在这10个总数中,是否有女性在旁边 这个怎么样:
library(zoo)
library(tidyverse)
isWoman <- c(rep(FALSE, 40), rep(TRUE, 10)) # the vector to sample from
twoAdjacent <- function(x) rollsum(x, 2) >= 2 # a helper function that calculates for a logical vector whether two TRUEs are next to each other
# and now the simulation (see explanation below)
replicate(
10000
, isWoman %>% sample() %>% twoAdjacent() %>% any() %>% `!`) %>%
mean()
图书馆(动物园)
图书馆(tidyverse)
isWoman%sample()%%>%Two相邻()%%>%any()%%>%`!`%%>%
平均数()
因此,重要的是要理解%%>%%
(管道操作符):将其读作“then”。先读第三行:
- 我们取向量
isWoman
- 随机排序(
)sample()
- 请参阅检查是否有两个相邻的
s(TRUE
)twonnextant()
- 检查是否出现
whereany
- 并应用逻辑NOT(
)!
我们复制了10000次,这给了我们一个长度为10000的逻辑向量。最后,我们将这个(逻辑)向量传递给
mean()
函数,其中每个TRUE
被解释为1
,每个FALSE
被解释为0
。因此,结果就是您正在寻找的概率 也许你可以试试下面的基本R码,其中M
是男性的,W
是女性的
M <- rep(0,40)
W <- rep(1,10)
nrep <- 1e5
# define your custom function that counts the event of no adjacent women
fcnt <- function(v) +all(diff(which(v==1))>1)
# use `mean` to calcuaute the frequency (or probability) of event
p <-mean(replicate(nrep,fcnt(sample(c(M,W)))))
M Hi user12110851。欢迎来到StackOverflow!请阅读相关信息以及如何给出建议。这样你可以帮助别人来帮助你!