Skip to content
Prev 391103 / 398506 Next

bootstraping by groups

Hello,

The error is in

boot.pop. <- boot(daT, bootprop, 999)


Here are basse R and tidyverse solutions. But first, create a test data 
set. The values in vector 'year' are the iris species names, I haven't 
changed them.


daT <- iris[3:5]
names(daT) <- c("BothTimes", "onlyoneTime", "year")


And the bootstrap function.


library(boot)

bootprop <- function(data, index){
   d <- data[index, ]
   sum(d[["BothTimes"]], na.rm = TRUE)/sum(d[["onlyoneTime"]], na.rm = TRUE)
}



1. Base R

Only one package needs to be loaded and the code is simple.


# split the data by year
sp <- split(daT, daT$year)
lapply(sp, \(x) boot(x, bootprop, 999)$t0)


2. tidyverse

Also load packagges dplyr and purrr. To call purrr::map_dfr an extra 
function is needed.


library(dplyr)
library(purrr)

boot_fun <- function(data, FUN, R){
   boot.prop <- boot(data, FUN, R)
   c(boot.prop = boot.prop$t0)
}

daT %>%
   group_split(year) %>%
   map_dfr(boot_fun, bootprop, R = 999)


Hope this helps,

Rui Barradas

?s 20:45 de 22/03/2022, Marna Wagley escreveu: