In my code below, if you keep increasing n, there is a point (in this example, n = 14) at which the sample() call inside the for loop breaks, throwing an error that n is larger than unique_study.
To prevent this automatically, can we internally (inside the for loop) change n to the nearest non-breakable number (in this example, n = 13)?
To be clear, 13 IS NOT given, user provides 14, program should find 13 and change n to 13.
library(tidyverse)
data <- expand_grid(study=1:40,group=1:2, time=0:4)
n = 14 # smaller than this will work
time_to_remove <- unique(data$time)[-(1:2)]
unique_study <- unique(data$study)
for(i in time_to_remove) {
studies_to_remove = sample(unique_study, size = n) # change `n` to 13 HERE
unique_study <- setdiff(unique_study, studies_to_remove)
dat <- data %>%
filter(
!( study %in% studies_to_remove &
time >= i ))
}
Aucun commentaire:
Enregistrer un commentaire