Last active
August 22, 2019 13:33
-
-
Save VEZY/babd21542ba13ff887ebf2299cab43cc to your computer and use it in GitHub Desktop.
R's expand.grid() equivalent in Julia
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using DataFrames | |
""" | |
Create a Data Frame from All Combinations of Factor Variables (see R's base::expand.grid) | |
# Arguments | |
... Array, Dict, or Tuple containing at least one value | |
# Return | |
A DataFrame containing one row for each combination of the supplied argument. The first factors vary fastest. | |
# Examples | |
```julia | |
expand_grid([1,2],["owl","cat"]) | |
expand_grid((1,2),("owl","cat")) | |
expand_grid((1,2)) # -> Returns a DataFrame with 2 rows of 1 and 2. | |
``` | |
""" | |
function expand_grid(args...) | |
nargs= length(args) | |
if nargs == 0 | |
error("expand_grid need at least one argument") | |
end | |
iArgs= 1:nargs | |
nmc= "Var" .* string.(iArgs) | |
nm= nmc | |
d= map(length, args) | |
orep= prod(d) | |
rep_fac= [1] | |
# cargs = [] | |
if orep == 0 | |
error("One or more argument(s) have a length of 0") | |
end | |
cargs= Array{Any}(undef,orep,nargs) | |
for i in iArgs | |
x= args[i] | |
nx= length(x) | |
orep= Int(orep/nx) | |
mapped_nx= vcat(map((x,y) -> repeat([x],y), collect(1:nx), repeat(rep_fac,nx))...) | |
cargs[:,i] .= x[repeat(mapped_nx,orep)] | |
rep_fac= rep_fac * nx | |
end | |
convert(DataFrame,cargs) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment