Code Generator | M (Power Query)

generateConditionalColumn

This function creates a conditional column in a table based on specific conditions in two different columns. The user specifies the source table, column names for condition evaluation, new column name, and conditions. If both conditions are met,


Empty image or helper icon

Prompt

generate a conditional column based on specific conditions in 2 different columns

Answer

// Function: generateConditionalColumn
// Purpose: To create a conditional column based on specific conditions in 2 different columns
// Parameters: 
//      sourceTable: The table containing the data
//      column1: The name of the first column for condition evaluation
//      column2: The name of the second column for condition evaluation
//      newColumnName: The name of the new conditional column to be added
//      condition1: The condition for column1 (e.g. each [column1] > 100)
//      condition2: The condition for column2 (e.g. each [column2] = "High")
// Return Type: table
// Exceptions: 
//      If the specified columns do not exist in the source table, an error will be raised.

generateConditionalColumn = (sourceTable as table, column1 as text, column2 as text, newColumnName as text, condition1 as logical, condition2 as logical) as table =>
    let
        // Add a conditional column based on the specified conditions
        newTable = Table.AddColumn(sourceTable, newColumnName, each if condition1 and condition2 then "ConditionMet" else "ConditionNotMet")
    in
        newTable;

Example Usage:

// Create a new conditional column based on conditions in columns Column1 and Column2
generateConditionalColumn(sourceTable, "Column1", "Column2", "NewConditionalColumn", each [Column1] > 100, each [Column2] = "High")

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This function creates a conditional column in a table based on specific conditions in two different columns. The user specifies the source table, column names for condition evaluation, new column name, and conditions. If both conditions are met, the new column value is "ConditionMet"; otherwise, it's "ConditionNotMet". If the specified columns do not exist, an error is raised.