【发布时间】:2019-06-21 18:45:45
【问题描述】:
我想创建一个具有三个参数的函数:样本大小、样本数量、伯努利试验中成功的真实 p。
此函数将输出以下结果:p 的平均估计值(即每个样本的 p 个估计值的平均值)、真实标准差的平均估计值(即每个样本的 sd 估计值的平均值)和最后是 95% CI 包含真实 p 的样本分数。
我想出了以下代码:
draw_function <- function(si=1, proba= 0.5){
sample_draw <- rbinom(n= si, 1, prob= proba)
mean_estimate <- mean(sample_draw)
s_estimate <- sqrt(mean_estimate*(1-mean_estimate))
confidence_interval <- list(c(mean_estimate -
1.96*s_estimate/sqrt(si), mean_estimate + 1.96*s_estimate/sqrt(si)))
list(mean_sample = mean_estimate, s_sample = s_estimate, c_sample =
confidence_interval)
}
draw_sample <- function(s=1, r=1, p=0.5) {
for (i in 1:r) {
inter <- list(mean_p=c(), mean_s = c(), mean_c = c() )
samp <- draw_function(si=s, proba= p)
inter$mean_p = c(inter$mean_p, samp$mean_sample)
inter$mean_s = c(inter$mean_s, samp$s_sample)
inter$mean_c <- c(inter$mean_c, samp$c_sample)
if ( inter[[3]][1] > p & inter[[3]][2] < p ) {
mean_c <- (mean_c + 1)/i
}
else {
meanc <- (mean_c + 0)/i
}
}
return(list(mean(inter$mean_p), mean(inter$mean_s), inter$mean_c))
但是,即使在修改了引起我注意的错误之后,此代码也无法正常工作。
我不断收到此错误:
draw_sample 中的错误(s = 30,r = 1000,p = 0.05):
(list) 对象不能被强制输入'double'
因此,我很想寻求您的帮助以找到问题并构建这样的功能!谢谢!
【问题讨论】:
标签: r statistics bernoulli-probability