我正在尝试编写一个具有四个输入的不公平抛硬币的函数:获得正面的重量/概率,模拟次数,每个模拟的翻转次数以及我想找到的正面确切数目获得的可能性。
下面的函数返回翻转部分我不了解的错误:
如果if(percent_heads == nheads)计数器<-计数器+ 1: 条件的长度> 1,并且仅第一个元素将使用50
counter = 0
percent_heads = NULL
flip_function <- function(p, nheads, nflips, nsim){
for(i in 1:nsim){
flips <- sample(c("H","T"), size = nflips, replace = TRUE, prob = c(p, 1-p))
percent_heads[i] <- length(which(flips == "H")) / nflips
if(percent_heads == nheads) counter <- counter + 1
}
return(counter/nsim)
}
答案 0 :(得分:0)
我认为我是个白痴。经过再三考虑后,我相信我可以使用它。有谁比我聪明,请验证此项目是否按预期进行:
counter = 0
total_heads = NULL
flip_function <- function(p, nheads, nflips, nsim){
for(i in 1:nsim){
flips <- sample(c("H","T"), size = nflips, replace = TRUE, prob = c(p, 1-p))
total_heads[i] <- length(which(flips == "H"))
if(total_heads[i] == nheads) counter <- counter + 1
}
return(counter/nsim)
}