0

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

# 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)
})

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

4

1 回答 1

0

也许像下面这样的东西可以满足您的需求。请注意,返回值是类对象列表的列表"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))
于 2019-03-21T15:35:17.233 回答