Skip to content

Instantly share code, notes, and snippets.

@DanChaltiel
Last active December 2, 2024 10:15
Show Gist options
  • Save DanChaltiel/0916932a4fb2656fce60e9dbb63ade7f to your computer and use it in GitHub Desktop.
Save DanChaltiel/0916932a4fb2656fce60e9dbb63ade7f to your computer and use it in GitHub Desktop.
Extention of [blockrand::blockrand]
#' Extention de [blockrand::blockrand]
#'
#' @param n_arm nombre de patient par bras
#' @param levels vecteur de bras de traitement
#' @param strata liste contenant les facteurs de stratification
#' @param block.sizes tailles de bloc possible (multiple du nombre de bras)
#' @param ... passé à [blockrand::blockrand]
#'
#' @author Dan Chaltiel (30/06/2023)
#' @return une tibble
#'
#' @examples
blockrand2 = function(n_arm, levels, strata, block.sizes = c(2,4,6), ...){
rlang::check_installed("blockrand")
wrong = block.sizes%%length(levels)!=0
if(any(wrong)){
cli::cli_abort(c(
"Some {.arg block.sizes} are not divisible by the number of treatment levels",
i="There are {.val {length(levels)}} treatment levels: {.val {levels}}",
i="{.arg block.sizes} {.val {block.sizes[wrong]}} {cli::qty(sum(wrong))} {?is/are} not
divisible by {.val {length(levels)}}"
))
}
expand.grid(strata) %>%
unite("strata", everything(), sep="__") %>%
pull(strata) %>%
map(~{
blockrand::blockrand(n = n_arm,
levels = levels,
stratum = .x,
id.prefix = paste(.x, " - "),
block.sizes = block.sizes/length(levels), ...)
}) %>%
list_rbind() %>%
separate(stratum, into=names(strata), sep="__") %>%
mutate(id = as.character(id)) %>%
as_tibble()
}
# Exemple 1 -----------------------------------------------------------------------------------
# autre exemple sur https://bookdown.org/pdr_higgins/rmrwr/randomization-for-clinical-trials-with-r.html
library(tidyverse)
set.seed(42)
strat = list(age=c("<=18", ">18"),
stage=c("I", "II", "III"),
country=c("group1", "group2", "group3"))
rando = blockrand2(n_arm=150, levels=c("SOC", "SOC+exp"),
strata=strat, block.sizes = c(4, 8))
cli::cli_inform("Calculating stratified randomisation for {prod(lengths(strat))} strata.")
print(rando)
rando %>%
select(all_of(names(strat)), treatment) %>%
mutate(across(everything(), ~as.numeric(factor(.x)))) %>%
write.csv2("rando.csv")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment