Skip to content

Instantly share code, notes, and snippets.

@muschellij2
Created August 15, 2019 17:37
Show Gist options
  • Select an option

  • Save muschellij2/96345cafc35ec8be8ddd008a7edd8765 to your computer and use it in GitHub Desktop.

Select an option

Save muschellij2/96345cafc35ec8be8ddd008a7edd8765 to your computer and use it in GitHub Desktop.
library(dplyr)
if (getRversion() >= "3.6.0") {
set.seed(234)
} else {
# RNGversion("3.5.0")
set.seed(1)
}
# creating example data
n = 20
ids = 1:n
reps = sample(1:5, size = n, replace = TRUE)
df = tibble(id = rep(ids, reps))
df = df %>%
group_by(id) %>%
mutate(visit = 1:n()) %>%
ungroup() %>%
mutate(outcome = rnorm(n()))
## bootstrap
# just get the unique IDs
id_df = df %>%
select(id) %>%
distinct()
# this bootstrap samples with replacement
boot = id_df %>%
sample_n(size = n(), replace = TRUE) %>%
group_by(id) %>% # need to group for mutate below
mutate(index = 1:n()) %>% # get the index for duplicate number
arrange(id) # not necessary but let's you see the indices
# join them together, only ids in boot will be kept, but
# will be duplicated because index is unique for each ID
this_boot = left_join(boot, df) %>%
arrange(id, visit, index)
library(dplyr)
if (getRversion() >= "3.6.0") {
set.seed(234)
} else {
# RNGversion("3.5.0")
set.seed(1)
}
# creating example data
n = 20
ids = 1:n
reps = sample(1:5, size = n, replace = TRUE)
df = tibble(id = rep(ids, reps))
df = df %>%
group_by(id) %>%
mutate(visit = 1:n()) %>%
ungroup() %>%
mutate(outcome = rnorm(n()))
## bootstrap
# just get the unique IDs
id_df = df %>%
select(id) %>%
distinct()
# this bootstrap samples with replacement
boot = id_df %>%
sample_n(size = n(), replace = TRUE) %>%
group_by(id) %>% # need to group for mutate below
mutate(index = 1:n()) %>% # get the index for duplicate number
arrange(id) # not necessary but let's you see the indices
# join them together, only ids in boot will be kept, but
# will be duplicated because index is unique for each ID
this_boot = left_join(boot, df) %>%
arrange(id, visit, index)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment