Power BI Power Query R

How to create group index with Power Query or R

It is possible to generate a group index (unique row ids) by one or many groups in Power Query. It comes handy when you have to detect the first or last record in each group. Here is 2 solutions: group index with M language and group index with R.

Group index in Power Query with M language.

1. Sort data in the order that you want to index.

2. Group your data by columns and return all rows in a new column named “Rows”.

3. Go to Advanced editor and add a new line of code that can generate indices in all the previously grouped tables.

Indexed = Table.TransformColumns(#"Grouped Rows", {{"Rows", each Table.AddIndexColumn(_,"GroupIndex", 1, 1)}})

4. Click on the expand icon and check all columns that are needed.

Here is all the M code that you can put in a blank query.

Group index by running R script in PowerQuery.

If you have experience with R, then this task will be easy for you, because there is rowid function in data.table package. You can choose one or many columns to group data and create unique row ids within each group.

1. Make sure that R script works (i prefer to test it first in RStudio) and your dataset is sorted in a way that you want to make indices.

2. Go to Transform -> Run R script

Paste your R script, use “dataset” to get your data and record result in a new dataset (you can name it as you like).

3. Press OK.

Make sure that data sources are set to public and if you need to publish that please check if R library is available in Power BI service. In this case library data.table is available.

Here is all the M code that you can put in a blank query.

2 comments on “How to create group index with Power Query or R

  1. Thank you for the clear tutorial and for giving it in both M and R.

  2. Thank you for sharing. You helped me out today.

Leave a Reply

Your email address will not be published. Required fields are marked *