Power BI Functions — (List.MaxN, R-slice_max, TOPN) | by Peter Hui | Towards Data Science

Top N by groups. I personally think it’s a very underrated way of exploring data. It’s like a saw, you just want to saw off the first few rows of a data set for analysis. I’m sure you have had to group summaries before, but you can also do some cool EDA with it using Power BI.
If you are able to group the data you have, get the difference of the top 2 items by the group, you almost always find something interesting there. Sometimes the “magic” happens when you see a big difference between specific groups and you begin asking yourself why.
Here in this article, I want to lay out a few methods you can use to get Top N by any grouping -
Use Power Query’s List.MaxN to get the top n by groups.Use top_n / slice_max in R — incorporate that into a Power Query scriptUse visuals and filters to get Top N by groups.Use a calculated column to get Top N by groups.(combination of COUNTROWS, ALLEXCEPT and EARLIER)
Use Power Query’s List.MaxN to get the top n by groups.
Use top_n / slice_max in R — incorporate that into a Power Query script
Use visuals and filters to get Top N by groups.
Use a calculated column to get Top N by groups.(combination of COUNTROWS, ALLEXCEPT and EARLIER)
Let’s take a look at the function in Power BI, you know I love Power Query, so let’s start there.
I have a simple table here — a list of units by company.
Basically, I want to rejig this simple data frame into a table that has 2 rows of each company.
Company A should display 21 and 4. Company B should display 44 and 33 and finally, Company C should display 66 and 22.
If you use power query, you gotta love the group by function :)
There is one problem though — the group by feature here only allows you to group by Max, Sum and Count, etc but doesn’t allow you to display the Max 2 by group, or Max 3 by group and so on.
What do you do?
Hmm.. let’s still use the group by and use the Max for now. Summarizing by Max only provides a summary like this.
It’s not exactly what we want. We want top 2 by group. ( Top 2 by company A, B,C)
Here is a tip — you may not know every Power Query functions, that’s okay, you just need to use the UI to get you close to where you need to go and then tweak it from there.
Here I will tweak the List.Max function. Instead of List.Max, I now used List.MaxN and add 2 in the parameter.
List.MaxN takes a list as input and a count as a second input.
Here we have the [Units] as a list and 2 is the N number we wish to return.
Now it returns a list of the 2 max values by group.
We will expand this column though, so we can do this by copying the result into a new column.
Let’s expand it and it’ll get us to what we want.
Simple right? We now have top 2 by [Company].
You can also do the same by running an R script.
You can do this via Transform > Run R Script. You will need to have R downloaded first. This is where you can find some info on downloading it.
To run the R script — select the Run R script ribbon and it will give you an empty dialogue box.
Here, you will need to load your R package and run the script.
This message at the top is saying the current table is called “dataset”.
Let’s add in our script.
I love the Tidyverse — here the script reads,
Load the dplyr package.
Take the dataset, group it by Company, then take the top_n or top 2 in this case of each group and return it in a table called “New”
and ta da!
Side note: you can also use slice_max which is the most current function since top_n has been superseded. You can just replace top_n with slice_max
How about top n without Power Query and just straight in Power BI?
If you want the Top 2 for each company, you can simply drag in the columns of company and units into the visualization pane using the table visual.
Step 1 — After you have loaded in your data — select the table visual.
Step 2 — put in the columns [Company] and [Units]. I jazzed it up a bit using the table styles.
Step 3 — Select Top N and input 2 since we want to see the top 2 by group and the value being evaluated is [Units].
You will get this —
Wait a minute — that doesn’t make sense! I want the top 2 by group, not all of the groups.
This is the great thing about Power BI — you can add in a filter to change the context of the entire visual. ( A single visual, single page or all pages for that matter)
Select a company and it will give you the top 2 in [Company] A, B or C.
On the side panels, if you prefer, you can use those buckets as filters as well if you don’t want the filters to be displayed on the page itself.
Now another way of doing this is using COUNTROWS and display this as a calculated column.
I always believe that calculated columns should be done for categories you want to slice and dice by. Here is an article if that helps. Here, we can slice and dice by the ranking of 1 and 2.
I’ll insert a new column using the below formula.
Ranking_Column = CALCULATE(  COUNTROWS('Table (3)'),     FILTER( ALLEXCEPT('Table (3)','Table (3)'[Company]),              'Table (3)'[Units] >= EARLIER('Table (3)'[Units]))         )
It’s a bit complicated — but these are the functions you will need to know.
COUNTROWS — it counts rows.
ALLEXCEPT — it’s a grouping function, if you use it for ‘Table (3)’[Company], it will group the [Company] column for measures you will use.
EARLIER — it’s somewhat like R lag function but not exactly, since the order of the evaluation doesn’t change the the value of the column is sorted.
FILTER — returns a table, according to your filter conditions.
In Power BI, when you see a FILTER function, read it from there first. Here the script reads,
Return a table that creates a grouping of [Company] using ALLEXCEPT and compare the [Units] using EARLIER. Then count the rows of the units column of units that have the same value or more using COUNTROWS.
The result once filtered will give you this.
You can then build measures based on the ranking of 1 and 2 and go from there.
What do I do with this?
Ask yourself — at your work and the dataset you deal with, did you only take the max or min of a group summarized it, and reported it? Maybe comparing the top 2 will give you something interesting.
There you have it — a simple Top n analysis using Power Query, R, and Power BI.
Thank you everyone for the claps and ‘Hello’ to all the new followers :)
I hope to write these articles every 2 weeks or so. I learn a lot from writing these and I hope you learn something from them too.
Be safe! Take care of yourself and good luck with your data journey!