寻找一种循环遍历数据集列以计算多个置信区间的方法(要插入到新列中)

Looking for a way to loop through columns of a dataset to calculate multiple confidence intervals (to be inserted to a new column)

我正在使用 PropCIs 包计算 R 中的置信区间。到目前为止,我正在单独计算这些,分别 运行 exactci 函数并手动提取上下置信区间。考虑到我有一个大数据集,这非常耗时。

我想一个循环会有助于使这个简单明了,但我希望得到有关如何执行它的建议。

到目前为止,这是我的代码:

#Creating a dummy data frame
success<-c(5,20,30)
n<-c(300,300,300)
data<-data.frame(success, n)

#Here I have been manually entering the data to the exactci function
library(PropCIs)
exactci(5,300, conf.level=0.95)
exactci(20,300, conf.level=0.95)
exactci(30,300, conf.level=0.95)

我如何使用循环执行此操作,同时向我的数据框添加两个额外的列来存储输出(置信区间上限和下限)?

您可以使用任何 apply* 循环:

library(PropCIs)
data[c('lower.ci', 'upper.ci')] <- t(mapply(function(x, y) 
        exactci(x,y, conf.level=0.95)$conf.int, data$success, data$n))
data

#  success   n lower.ci upper.ci
#1       5 300 0.005433  0.03846
#2      20 300 0.041194  0.10109
#3      30 300 0.068492  0.13967

因为exactci产生一个htest对象,你也可以使用broompurrr

library(purrr)
library(broom)
library(PropCIs)

map2_df(.x = data$success,
        .y = data$n,
        ~ broom::tidy(exactci(.x,
                              .y,
                              conf.level = .95)
        )) %>% 
   cbind(data, .)
#>   success   n    conf.low  conf.high
#> 1       5 300 0.005433205 0.03846374
#> 2      20 300 0.041194016 0.10108565
#> 3      30 300 0.068491684 0.13967331

您的数据

data <- data.frame(success = c(5,20,30), 
                   n = c(300,300,300)
                   )