Split to chunks of size n
Arguments
- d
data. Can be vector or data frame.
- n
number of chunks
- label
naming prefix for chunk names
- even
boolean to set if size of chunks should be evenly distributed.
- pattern
regex pattern to extract names from provided vector. If data frame, will assume first column is name.
Examples
tail(chunks_of_n(seq_len(100),7),3)
#> $`13`
#> [1] 85 86 87 88 89 90 91
#>
#> $`14`
#> [1] 92 93 94 95 96 97 98
#>
#> $`15`
#> [1] 99 100
#>
tail(chunks_of_n(seq_len(100),7,even=TRUE),3)
#> $`13`
#> [1] 83 84 85 86 87 88
#>
#> $`14`
#> [1] 89 90 91 92 93 94
#>
#> $`15`
#> [1] 95 96 97 98 99 100
#>
ds <- data.frame(nm=paste0("Sub",
sprintf("%03s", rownames(stRoke::talos))),stRoke::talos)
head(chunks_of_n(ds,7,pattern="Sub[0-9]{3}",label="grp"),2)
#> $`grp-NA-NA`
#> nm rtreat mrs_1 mrs_6 hypertension diabetes civil
#> 38 Sub 38 Active 1 1 no no partner
#> 434 Sub434 Active 1 1 yes no partner
#> 588 Sub588 Active 2 2 yes no partner
#> 42 Sub 42 Active 0 0 yes no partner
#> 160 Sub160 Placebo 1 1 yes no partner
#> 174 Sub174 Active 0 1 yes no alone
#> 11 Sub 11 Placebo 2 1 yes yes alone
#>
#> $`grp-Sub601-NA`
#> nm rtreat mrs_1 mrs_6 hypertension diabetes civil
#> 601 Sub601 Placebo 1 1 no no partner
#> 412 Sub412 Active 0 0 yes no partner
#> 88 Sub 88 Placebo 1 1 yes yes partner
#> 56 Sub 56 Placebo 0 0 no no alone
#> 235 Sub235 Placebo 2 1 yes yes alone
#> 205 Sub205 Active 3 3 no no partner
#> 62 Sub 62 Active 2 2 yes no alone
#>
## Please notice that no sorting is performed. This is on purpose to preserve
## original sorting. If sorting is intended, try something like this:
ds[order(ds$nm),] |> chunks_of_n(7,pattern="Sub[0-9]{3}",label="grp") |>
head(2)
#> $`grp-NA-NA`
#> nm rtreat mrs_1 mrs_6 hypertension diabetes civil
#> 1 Sub 1 Placebo 0 0 yes no partner
#> 2 Sub 2 Placebo 2 1 no no partner
#> 7 Sub 7 Placebo 1 1 yes no partner
#> 9 Sub 9 Placebo 1 1 no no partner
#> 11 Sub 11 Placebo 2 1 yes yes alone
#> 13 Sub 13 Active 1 1 yes no partner
#> 20 Sub 20 Placebo 1 2 no no alone
#>
#> $`grp-NA-NA`
#> nm rtreat mrs_1 mrs_6 hypertension diabetes civil
#> 22 Sub 22 Placebo 2 1 no no partner
#> 26 Sub 26 Placebo 2 4 no no alone
#> 28 Sub 28 Active 2 2 yes no partner
#> 29 Sub 29 Placebo 2 2 no no alone
#> 33 Sub 33 Placebo 0 0 yes no alone
#> 34 Sub 34 Active 1 1 no no alone
#> 38 Sub 38 Active 1 1 no no partner
#>