Skip to content

Commit

Permalink
change implemetation
Browse files Browse the repository at this point in the history
  • Loading branch information
pdeffebach committed Dec 22, 2023
1 parent e285f83 commit b381960
Showing 1 changed file with 10 additions and 50 deletions.
60 changes: 10 additions & 50 deletions src/macros.jl
Original file line number Diff line number Diff line change
Expand Up @@ -3008,38 +3008,18 @@ macro rename!(x, args...)
esc(rename!_helper(x, args...))
end

function fix_c(x)
c = get_column_expr(x; allow_multicol = true)
if isnothing(c)
throw(ArgumentError("Invalid column selector in @groupby"))
end
c
end

function groupby_helper(df, args...)
cols = map(fix_c, args)
t = Expr(:tuple, cols...)
t = Expr(:tuple, args...)
:($groupby($df, ($Cols($t...))))
end

function groupby_helper(df, arg::Expr)
if arg isa Expr && arg.head == :block
argsvec = MacroTools.rmlines(arg).args
return groupby_helper(df, argsvec...)
else
c = fix_c(arg)
return :($groupby($df, $c))
end
end


"""
groupby(df, args...)
Group a data frame by columns. Similar
Group a data frame by columns. An alias for
```
groupby(df, [args...])
groupby(df, Cols(args...))
```
but with a few convenience features.
Expand All @@ -3050,41 +3030,21 @@ but with a few convenience features.
generation of new columns. New column generation must be done
before `@groupby` is called.
Unlike `DataFrames.groupby`, `@groupby` allows mixing of `Symbol`
and `String` inputs, such that `@groupby df :A $DOLLAR"B"`
is supported. However integers cannot be mixed with strings or symbols.
`@groupby(df, :A, 1)` fails.
`@groupby` allows mixing of `Symbol`
and `String` inputs, such that `@groupby df :A "B"`
is supported.
To use vectors as a single argument for grouping, escaping with `$DOLLAR`
must be used. `@groupby df [:a, :b]` fails. Rather, use `@groupby df $DOLLAR[:a, :b]`.
This behavior ensures consistency with other DataFramesMeta.jl macros.
`@groupby` automatically concatenates together multiple inputs such that mixing
vector and scalar column selectors is supported, as in `@groupby df :A $DOLLAR[:B, :C]`
`@groupby` also allows for the "block" style of DataFramesMeta.jl macros,
as in
```
@grouby df begin
:A
:B
end
```
Arguments are not escaped and DataFramesMeta.jl rules for column
selection, such as `$DOLLAR` for escaping, do not apply.
## Examples
```julia-repl
julia> df = DataFrame(A = [1, 1], B = [3, 4], C = [6, 6]);
julia> @groupby df :A;
julia> @groupby df :A :B;
julia> @groupby df $DOLLAR[:A, :B];
julia> @groupby df begin
:A
:B
end;
julia> @groupby df :A $DOLLAR[:B, :C];
julia> @groupby df [:A, :B];
julia> @groupby df :A [:B, :C];
```
"""
macro groupby(df, args...)
esc(groupby_helper(df, args...))
Expand Down

0 comments on commit b381960

Please sign in to comment.