Learn R Programming

RcppAlgos (version 2.9.3)

comboGrid: Unordered Cartesian Product

Description

Efficient version of expand.grid where order does not matter. This is a combinatorial variant where groups of elements are treated as equivalent regardless of order. For example, given: {1, 2}, {1, 2}, the unordered Cartesian product is {1, 1}, {1, 2}, {2, 2}. It is loosely equivalent to the following:

  • t = expand.grid(lst)

  • t = t[do.call(order, t), ]

  • key = apply(t, 1, function(x) paste0(sort(x), collapse = ""))

  • t[!duplicated(key), ]

Usage

comboGrid(..., repetition = TRUE, return_df = FALSE)

Value

When all of the input is of the same type, by default comboGrid produce a matrix (a data.frame otherwise). This can be ignored by setting the argument return_df = TRUE.

Arguments

...

vectors, factors or a list containing these. (See ?expand.grid).

repetition

Logical value indicating whether results should be with or without repetition. The default is TRUE.

return_df

Logical flag to force the output to be a data.frame. The default is FALSE.

Author

Joseph Wood

See Also

expandGrid

Examples

Run this code
## description example
lst = list(1:2, 1:2)

t = expand.grid(lst)
t = t[do.call(order, t), ]
key = apply(t, 1, function(x) paste0(sort(x), collapse = ""))
t[!duplicated(key), ]

## vs using comboGrid. N.B. Output is a matrix
comboGrid(lst)

## Force a data.frame to be returned
comboGrid(lst, return_df = TRUE)

## Input vectors are of different type, so a data.frame is returned
expGridNoOrder = comboGrid(1:5, 3:9, letters[1:5], letters[c(1,4,5,8)])
head(expGridNoOrder)
tail(expGridNoOrder)

expGridNoOrderNoRep = comboGrid(1:5, 3:9, letters[1:5],
                                letters[c(1,4,5,8)], repetition = FALSE)

head(expGridNoOrderNoRep)
tail(expGridNoOrderNoRep)

Run the code above in your browser using DataLab