在 Julia 中重现 R 的 `expand.grid` 函数

问题描述 投票:0回答:5

expand.grid
R
中一个非常方便的函数,用于计算多个列表的所有可能组合。这是它的工作原理:

> x = c(1,2,3)
> y = c("a","b")
> z = c(10,12)
> d = expand.grid(x,y,z)
> d
   Var1 Var2 Var3
1     1    a   10
2     2    a   10
3     3    a   10
4     1    b   10
5     2    b   10
6     3    b   10
7     1    a   12
8     2    a   12
9     3    a   12
10    1    b   12
11    2    b   12
12    3    b   12

如何在 Julia 中重现这个函数?

r combinations julia
5个回答
4
投票

感谢@Henrik的评论:

x = [1,2,3]
y = ["a","b"]
z = [10,12]
d = collect(Iterators.product(x,y,z))

这是使用列表理解的另一个解决方案

reshape([ [x,y,z]  for x=x, y=y, z=z ],length(x)*length(y)*length(z))

2
投票

这是我完全(?)通用的解决方案,使用递归、可变参数和splatting:

function expandgrid(args...)
    if length(args) == 0
        return Any[]
    elseif length(args) == 1
        return args[1]
    else
        rest = expandgrid(args[2:end]...)
        ret  = Any[]
        for i in args[1]
            for r in rest
                push!(ret, vcat(i,r))
            end
        end
        return ret
    end
end

eg = expandgrid([1,2,3], ["a","b"], [10,12])
@assert length(eg) == 3*2*2
@show eg

这给出了一个数组的数组,但是如果您想要的话,您可以将其简单地组合成一个矩阵。


0
投票

我知道这是一个相当老的问题,但在找到这篇文章之前几天,我也几乎将 Expand.grid 函数从 R 转换为 Julia ...... 对于某些人来说它仍然很有趣,因为它返回一个

DataFrame
,这可能更方便。 这是指向要点的链接,这里是以防万一的代码:

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

0
投票

我知道这是一个老问题,但如果有人仍在寻找类似于 R Expand.grid 函数的解决方案(即传递任何类型的命名变量列表并返回一个数据框,其中变量名称作为列名称、原始变量类型的每一列以及不同变量的所有可能组合),这是我的 Julia 新手尝试:

using DataFrames

function expand_grid(; iters...)
    var_names = collect(keys(iters))
    var_itr = [1:length(x) for x in iters.data]
    var_ix = vcat([collect(x)' for x in Iterators.product(var_itr...)]...)
    out = DataFrame()
    for i = 1:length(var_names)
        out[:,var_names[i]] = collect(iters[i])[var_ix[:,i]]
    end
    return out
end

expand_grid(a=1:2, b=1.0:5.0, c=["one", "two", "three", "four"])

很可能有一种更有效或更干净的方法来做到这一点,但这是我能想到的最好的方法,它可以满足我对 R 函数的期望。


0
投票
using DataFrames

function expand_grid(; kw...)
  values = [v for (_, v) in kw]
  names = keys(kw) |> collect
  DataFrame(collect(Iterators.product(values...))[:], names)
end

julia> dims = (x = 1:2, y = [3, 4], z = ["a", "b", "c"]);

julia> expand_grid(;dims...)
12×3 DataFrame
 Row │ x      y      z      
     │ Int64  Int64  String 
─────┼──────────────────────
   1 │     1      3  a
   2 │     2      3  a
   3 │     1      4  a
   4 │     2      4  a
   5 │     1      3  b
   6 │     2      3  b
   7 │     1      4  b
   8 │     2      4  b
   9 │     1      3  c
  10 │     2      3  c
  11 │     1      4  c
  12 │     2      4  c
© www.soinside.com 2019 - 2024. All rights reserved.