Forum Discussion

AKM_Crowley's avatar
AKM_Crowley
New Member
9 years ago
Solved

M Language - unpivot issue

Hello.  I am fairly new to the M language, so any tips are greatly appreciated.  I am  struggling with the following:   I have a risk table with data in it as follows:   ID    Risk               ...
  • MarcelBeug's avatar
    9 years ago

    You can first unpivot the likelihood columns and drill down into the value column so you have a list of unpivoted values.

    Next you take the Source again, remove the likelihood columns, unpivot the dollars, remove the "r"'s.

    Now you have to glue those parts together with Table.FromColumns.

    That requires the second table to be turned into records first.

    As finishing touches you need to expand the records and rename some columns.

     

    let
        Source = RiskTable,
        
        // First unpivot the likelihood columns:
        #"Unpivoted Columns" = Table.UnpivotOtherColumns(Source, {"ID", "Risk", "CY", "Yr2", "Yr3", "Yr4"}, "Attribute", "Value"),
        #"Renamed Columns" = Table.RenameColumns(#"Unpivoted Columns",{{"Value", "Likelihood"}}),
        Likelihood1 = #"Renamed Columns"[Likelihood],
    
        // Take the source again, remove the likelihood columns, unpivot and rem
        #"Removed Columns" = Table.RemoveColumns(Source,{"CYLikelihood", "Y2Likelihood", "Y3Likelihood", "Y4Likelihood"}),
        #"Unpivoted Columns1" = Table.UnpivotOtherColumns(#"Removed Columns", {"ID", "Risk"}, "Attribute", "Value"),
        #"Replaced Value" = Table.ReplaceValue(#"Unpivoted Columns1","r","",Replacer.ReplaceText,{"Attribute"}),
    
        // Glue the 2 parts together, expand the records and rename some columns:
        Custom2 = Table.FromColumns({Table.ToRecords(#"Replaced Value"),Likelihood1}),
        #"Expanded Column1" = Table.ExpandRecordColumn(Custom2, "Column1", {"ID", "Risk", "Attribute", "Value"}, {"ID", "Risk", "Attribute", "Value"}),
        #"Renamed Columns1" = Table.RenameColumns(#"Expanded Column1",{{"Attribute", "Year"}, {"Value", "Dollars"}, {"Column2", "Likelihood"}})
    
    in
        #"Renamed Columns1"