Bootstrap t.test: 对多个分组级别使用apply函数

Bootstrap t.test: Using apply function for multiple grouping levels

我需要 bootstrap 我的“自动化”lapply t.test 函数来计算 Bootstrap 统计数据(原始、偏差和标准误差)。这是基本的 t.test 到目前为止我得到的代码(没有 bootstrapping):

# create data
val<-runif(60, min = 0, max = 100)
distance<-floor(runif(60, min=1, max=3))
phase<-rep(c("a", "b", "c"), 20)
color<-rep(c("red", "blue","green","yellow","purple"), 12)

df<-data.frame(val, distance, phase, color)

# run function to obtain t.tests
lapply(split(df, list(df$color, df$phase)), function(d) {
  tryCatch({ t.test(val ~ distance, var.equal=FALSE, data=d) },
       error = function(e) NA)
})

效果很好。但是,我不确定如何将 bootstrap 方法合并到此应用函数中。

也许像下面这样的东西可以满足您的需求。请注意,return 值是 class "htest"(列表)或 NA.

对象列表的列表
boot_fun <- function(DF){
  n <- nrow(DF)
  i <- sample(n, n, TRUE)
  df <- DF[i, ]
  lapply(split(df, list(df$color, df$phase)), function(d) {
    tryCatch({ t.test(val ~ distance, var.equal=FALSE, data=d) },
             error = function(e) NA)
  })
}

set.seed(1234)
R <- 10
result <- lapply(seq_len(R), function(i) boot_fun(df))