juliajulia-dataframe

How to calculate mean of values per unique class


I have a dataframe:

sex   age
f     10
m     12
m     11
m     17
f     13
f     12
I     8

Want I want to calculate the mean of age per sex:

f=> mean age = (10+13+12) /3
m=> mean age = (12+11+17) /3
I=> mean age = 8

I am trying something like this:

combine(df, :age => mean => :mean_age, :sex => unique)

But all mean_age have the same value.


Solution

  • use groupby first:

    combine(groupby(df, :sex), :age => mean => :mean_age)
    

    or using DataFramesMeta.jl

    @chain df begin
        groupby(:sex)
        @combine(:mean_age = mean(:age))
    end