Forum Discussion

Anonymous's avatar
Anonymous
Not applicable
6 years ago
Solved

Power M Query custom aggregate function to return most common value within a group

Can anyone help me? To come up with a custom aggregate function to return the most common value for one or more columns for a set of records which have a unique grouping: ie that you can use where yo...
  • Anonymous's avatar
    Anonymous
    6 years ago

    Here is the answer I came up with. I have never written a Power M Query function definition so all feedback on style and performance welcome.

    I think it is a useful function for when your data is mostly correct but you need to take the common value.

     

    The logic of the function is:

    1.  get the unique values and convert to table
    2.  find number of times each occurs in the input
    3.  Sort by descending and return the string in the first row - the most commonly occuring string

    I could add something for how nulls are handled (eg ignore null if top string and return next one down) but this seems to work for me

     

    Function is MostCommon (you have to name the query)

     

    let 
    fnMostCommon = (ListIn)  =>
    let
    uniquevalues=List.Distinct(ListIn),
    result=Table.FromList(uniquevalues,null,{"u"}),
    result2=Table.AddColumn(result ,"freq", each List.Count(List.PositionOf(ListIn, [u], 100))),
    result3 = Table.Sort(result2,{"freq", Order.Descending}),
    result4 = List.First(result3[u])
    in result4
    in fnMostCommon

     

    And the test harness is:

     

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WSlTSUQozhBCxOlC+ETa+EZifhKY+CVl9LAA=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type text) meta [Serialized.Text = true]) in type table [G1 = _t, A1 = _t, A2 = _t]),
        #"Changed Type" = Table.TransformColumnTypes(Source,{{"G1", type text}, {"A1", type text}, {"A2", type text}}),
        #"Grouped Rows" = Table.Group(#"Changed Type", {"G1"}, {{"Agg", each MostCommon([A1]), type text}, {"Agg2", each AllConcat([A1]), type text}}),
        a = #"Grouped Rows"{[G1="a"]}[Agg]
    in
        a