对我来说看起来很合理。不过,您不需要replicate。我个人会设置一个全局n:
set.seed(123)
## predicted response
n <- 50
y_pred <- rbinom(n, 1, prob=.55)
## calculate actual probability of predicted response
sum(y_pred) / length(y_pred)
# [1] 0.54
## actual response
y <- sample(rep(0:1, each=n/2))
## calculate actual probability of actual response
sum(y) / length(y)
# [1] 0.5
table(y, y_pred)
# y_pred
# y 0 1
# 0 13 12
# 1 10 15
但是,在如此小的n 上,您预测响应的实际概率可能会有很大的随机波动(即取决于种子),尤其是在较小的n 上。让我们把代码放到一个函数中来展示一下。
n <- 50
sfun <- function() {
y_pred <- rbinom(50, 1, prob=.55)
sum(y_pred) / length(y_pred)
}
set.seed(383159)
sfun()
# [1] 0.62 ## 13% off!
set.seed(82809)
sfun()
# [1] 0.44 ## 20% off!
您可以做的是使用repeat 循环,如果结果在集合tolerance 内,则该循环会中断。 (注意,当tol 设置得太小时,这将永远运行!)
tol <- .01
set.seed(123)
n <- 50
repeat({
y_pred <- rbinom(n, 1, prob=.55)
pr1 <- sum(y_pred) / length(y_pred)
if (pr1 <= .55 + tol & pr1 >= .55 - tol)
break
})
y_pred
# [1] 1 0 1 0 0 1 1 0 0 1 0 1 0 0 1 0 1 1 1 0 0 0 0 0 0 0 1 0 1 1 0 0 0 0
# [35] 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0
sum(y_pred) / length(y_pred)
# [1] 0.54 ## ok!