assign_groups: Assign elements in a vector to groups

View source: R/vector_tools.R

assign_groupsR Documentation

Assign elements in a vector to groups

Description

In contrast to desiderata::split_size() which splits a vector into an arbitrary number of chunks as long as each chunk has n or fewer entries inside it, desiderata::assign_groups() splits the vector into n chunks, possibly with a different number of entries per chunk.

Usage

assign_groups(vec, g, balance = TRUE, dedupe = TRUE)

Arguments

vec

(Numeric or Character) A vector. No sorting is done to the vector so if you want to group based on some kind of ordering, you need to do it beforehand.

g

(Integer) The maximum of of groups to split vec into (the maximum group size may not be reached, e.g. grouping 4 elements into 6 groups).

balance

(Logical) If TRUE, try to have equal numbers of observations per group.

dedupe

(Logical) If TRUE, duplicate values in vec will be ignored when generating the groups, ensuring that identical values go into the same group. This can unbalance the groups even if balance = TRUE.

Value

An integer vector of the same length as vec.

Examples

testvec <- c(4, 7, 8, 2, 2, 2, 5, 1, 6, 3)

# 10 values assigned to 4 balanced groups.
assign_groups(testvec, 4, balance = TRUE, dedupe = FALSE)
#> [1] 1 1 1 2 2 2 3 3 3 4

# 10 values assigned to 4 unbalanced groups.
assign_groups(testvec, 4, balance = FALSE, dedupe = FALSE)
#> [1] 1 1 1 1 2 2 3 3 4 4

# 8 values (plus 2 duplicates) assigned to 4 groups.
assign_groups(testvec, 4, balance = TRUE, dedupe = TRUE)
#> [1] 1 1 2 2 2 2 3 3 4 4


DesiQuintans/desiderata documentation built on April 9, 2023, 5:43 a.m.