samedi 18 juillet 2020

Bootstrapping a simple function in R

I have a simple function called foo. To bootstrap it (randomly shuffle it), I use library boot using the instructions HERE. But it looks like I have an indexing problem because I get the following error:

number of items to replace is not a multiple of replacement length, is this fixable?

library(boot)
foo <- function(X) {
  X <- as.matrix(X)
 tab <- table(row(X), unlist(X))
 w <- diag(ncol(tab))
 rosum <- rowSums(tab)
 obs_oc <- tab * (t(w %*% t(tab)) - 1)
 obs_c <- colSums(obs_oc)
 max_oc <- tab * (rosum - 1)
 max_c <- colSums(max_oc)
 SA <- obs_c / max_c
 h <- names(SA)
 h[is.na(h)] <- "NA"
 setNames(SA, h)
 }  
 # EXAMPLE OF USE:
 dat <- data.frame(a = 1:4, b = c(2,1, 3, 4))

 foo(dat)

 # Tried the following to bootstrap it:

 boot_fun <- function(data, i){

  resample <- data[i, ,drop = FALSE]
  foo(resample)
 }

boot::boot(
 data = dat,
statistic = boot_fun,
R = 200)



Aucun commentaire:

Enregistrer un commentaire