Q:

Aggregate a data frame by values of column that meet a condition

Suppose I have the following DataFrame in Julia, named A:

│ Row  │ x1  │ x2      │
├──────┼─────┼─────────┤
│ 1    │ 1.0 │ 5.78341 │
│ 2    │ 2.0 │ 5.05401 │
│ 3    │ 3.0 │ 4.79754 │
│ 4    │ 4.0 │ 4.4126  │
│ 5    │ 5.0 │ 4.29433 │
│ 6    │ 6.0 │ 4.14306 │
│ 7    │ 1.0 │ 5.94811 │
│ 8    │ 2.0 │ 5.0432  │
│ 9    │ 3.0 │ 4.78697 │
│ 10   │ 4.0 │ 4.40384 │
│ 11   │ 5.0 │ 4.29901 │
?
│ 3933 │ 2.0 │ 4.90528 │
│ 3934 │ 3.0 │ 4.57429 │
│ 3935 │ 4.0 │ 4.3988  │
│ 3936 │ 5.0 │ 4.19076 │
│ 3937 │ 6.0 │ 4.09517 │
│ 3938 │ 7.0 │ 3.96192 │
│ 3939 │ 1.0 │ 5.88878 │
│ 3940 │ 2.0 │ 5.87492 │
│ 3941 │ 3.0 │ 4.9453  │
│ 3942 │ 4.0 │ 4.39047 │
│ 3943 │ 5.0 │ 4.28096 │
│ 3944 │ 6.0 │ 4.13686 │
I want to calculate the mean of x2 values by x1 values only if the number of repetitions of x1 values in less or equal than 500, for example. I tried the following code, but it didn't work:
aggregate(A,length(:x1).<=500,mean)
If for example, only the values 1,2 and 3 meet the condition, the result should be:

│ Row  │ x1  │ x2      │
├──────┼─────┼─────────┤
│ 1    │ 1.0 │ 5.85264 │
│ 2    │ 2.0 │ 5.15852 │
│ 3    │ 3.0 │ 4.92586 │
where the x2 values are the corresponding mean values.
Any suggestions?

A:

I would use DataFramesMeta.jl here as it will be cleaner than using DataFrames.jl only functionality (I give two ways to obtain the desired result as examples):
using DataFramesMeta
# I generate a smaller DataFrame with cutoff of 15 for the example
df = DataFrame(x1=repeat([1,1,2,2,3], inner=10), x2=rand(50))

# first way to do it
@linq df |>
    groupby(:x1) |>
    where(length(:x1)>15) |>
    @based_on(x2=mean(:x2))

# other way to do the same
@linq df |>
    by(:x1, x2=mean(:x2), n=length(:x2)) |>
    where(:n.>15) |>
    select(:x1, :x2)

