Skip to content

Shuffle

Description

shuffle will reorder the input vector or matrix:

  • If the input is a row or column vector, the items are reordered and returned as a row or column vector
  • If the input is a matrix, rows are shuffled by default (ie rows are kept together but reordered). Optionally the matrix is shuffled by columns instead of rows.

The function uses runif with the default system seed. That means that the function is nonvolatile by default, and the seed is workbook-specific and depends on the cell address. See the documentation of runif for more detail.

Syntax

shuffle(data, [by_cols=FALSE]) where data is the input vector or matrix and by_cols is a boolean. The output has the same dimensions as the input.

Source Code

shuffle = LAMBDA(
    data,       // input row or column vector
    [by_cols],  // sort matrix by rows or columns? Default FALSE (sort matrix by rows)
    IFS(
        // if a vector, sort the items and return
        COLUMNS(data) = 1, SORTBY(data, runif(ROWS(data))),
        ROWS(data) = 1, SORTBY(data, runif(1, COLUMNS(data))),
        // it is a matrix, sort by rows (default) or columns as user specifies
        TRUE, LET(
            by_cols, IF(ISOMITTED(by_cols), FALSE, by_cols),
            // add random row or column for shuffling
            plusOne, IF(
                by_cols,
                VSTACK(runif(1, COLUMNS(data)), data),
                HSTACK(runif(ROWS(data)), data)
            ),
            shuffled, SORT(plusOne,,,by_cols),
            // remove the extra row or column before returning
            IF(
                by_cols,
                DROP(shuffled,1),
                DROP(shuffled,,1)
            )
        )
    )
);