You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R数据框逐行应用BinomCI批量计算二项分布置信区间

R 逐行计算二项分布置信区间并合并结果表

你可以直接用mapply(基础R方案,无需额外依赖包)或者rowwise(tidyverse方案,写法更直观)实现批量逐行计算,两种方案的可运行代码如下:

基础R实现方案

# 加载所需包
library(DescTools)

# 构造数据框,修正原代码中赋值符号避免列名异常
nine <- data.frame(
  N = c(118, 147,  63,  77, 141,  93, 639,  54,121, 143, 321, 639, 117, 522, 639,287,232, 120, 639),
  B = c(96, 103,  55,  62, 111,  76, 503,  37,94, 118, 254, 503,  93, 410, 503, 214, 192,  97, 503)
)

# 逐行配对传入B、N值计算置信区间,处理成统一格式
ci_result <- t(mapply(function(b, n) {
  round(BinomCI(b, n, conf.level = 0.95, method = "clopper-pearson"), 3) * 100
}, nine$B, nine$N))

# 转成数据框格式,可直接查看或导出
ci_df <- as.data.frame(ci_result, row.names = 1:nrow(nine))

# 如需和原始N、B列拼接,执行以下代码即可
# ci_df <- cbind(nine, ci_df)

print(ci_df)

tidyverse实现方案

如果平时习惯用tidyverse生态,可用rowwise语法实现,可读性更强:

library(DescTools)
library(dplyr)

nine <- data.frame(
  N = c(118, 147,  63,  77, 141,  93, 639,  54,121, 143, 321, 639, 117, 522, 639,287,232, 120, 639),
  B = c(96, 103,  55,  62, 111,  76, 503,  37,94, 118, 254, 503,  93, 410, 503, 214, 192,  97, 503)
)

ci_df <- nine %>%
  rowwise() %>%
  mutate(
    est = round(BinomCI(B, N, conf.level = 0.95, method = "clopper-pearson")[1],3)*100,
    lwr.ci = round(BinomCI(B, N, conf.level = 0.95, method = "clopper-pearson")[2],3)*100,
    upr.ci = round(BinomCI(B, N, conf.level = 0.95, method = "clopper-pearson")[3],3)*100
  ) %>%
  ungroup()

print(ci_df)

两种方案最终都会输出包含全部19行计算结果的表格,包含率估计值、95%置信区间上下限三个字段,已经完成乘100、保留三位小数的格式处理。


内容的提问来源于stack exchange,提问作者jonestats

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 15:54:02