expandGrid {RcppAlgos} | R Documentation |
Cartesian Product
Description
Generate the Cartesian Product of the input vectors. It is very similar to expand.grid
however there are some notable differences:
Produces lexicographic ordered output consistent with other functions in
RcppAlgos
. Compared toexpand.grid
where the first column varies the fastest,expandGrid
varies the first column the slowest.When all of the input is of the same type, by default
expandGrid
produce amatrix
(adata.frame
otherwise). This can be ignored by setting the argumentreturn_df = TRUE
.No attributes are added nor are strings converted to factors. In
expand.grid
we would achieve this by settingKEEP.OUT.ATTRS = FALSE
andstringsAsFactors = FALSE
.If it is possible to return a matrix, we can utilize the argument
nThreads
in order to produce results in parallel for maximal efficiency.
Usage
expandGrid(..., lower = NULL, upper = NULL,
nThreads = NULL, return_df = FALSE)
Arguments
... |
vectors, factors or a list containing these. (See |
lower |
The lower bound. Cartesian products are generated lexicographically, thus utilizing this argument will determine which specific product to start generating from (e.g. |
upper |
The upper bound. Similar to |
nThreads |
Specific number of threads to be used. The default is |
return_df |
Logical flag to force the output to be a |
Value
When all of the input is of the same type, by default expandGrid
produces a matrix
(a data.frame
otherwise). This can be ignored by setting the argument return_df = TRUE
.
Author(s)
Joseph Wood
See Also
Examples
## description example
lst = list(1:2, 1:2)
## Using base R
t = expand.grid(lst)
## vs using expandGrid. N.B. Output is a matrix
expandGrid(lst)
## Force a data.frame to be returned
expandGrid(lst, return_df = TRUE)
lst = Map(function(x, y) x:y, 8:14, 15:21)
## Use multiple threads for greater efficiency
system.time(expandGrid(lst, nThreads = 2))