I am trying to digest data to give me a visual in the following format
| Location ID | Type | Metric | This Month | Last Month | MoM % Change |
|---|---|---|---|---|---|
| 12345 | A | Metric 1 | 45 | 23 | 48.88% |
| 12345 | B | Metric 1 | 54 | 52 | 3.85% |
| 67890 | A | Metric 1 | 74 | 89 | -20.27% |
| 67890 | B | Metric 1 | 23 | 26 | -13.04% |
| 65432 | A | Metric 1 | 76 | 63 | 17.11% |
| 65432 | B | Metric 1 | 45 | 23 | 48.88% |
| 12345 | A | Metric 2 | 54 | 52 | 3.85% |
| 12345 | B | Metric 2 | 74 | 89 | -20.27% |
| 67890 | A | Metric 2 | 23 | 26 | -13.04% |
| 67890 | B | Metric 2 | 76 | 63 | 17.11% |
| 65432 | A | Metric 2 | 54 | 52 | 3.85% |
| 65432 | B | Metric 2 | 74 | 89 | -20.27% |
My data is currently in this format:
| Location ID | Type | Date | Metric1 | Metric2 | Metric3 | Metric4 | MetricN |
|---|---|---|---|---|---|---|---|
| 12345 | A | 08/31/2025 | 45 | 54 | 36 | 23 | 65 |
| 12345 | B | 08/31/2025 | 54 | 74 | 44 | 32 | 74 |
| 67890 | A | 8/31/2025 | 74 | 23 | 66 | 34 | 36 |
| 67890 | B | 8/31/2025 | 23 | 76 | 47 | 46 | 27 |
| 12345 | A | 7/31/2025 | 23 | 52 | 42 | 78 | 12 |
| 12345 | B | 7/31/2025 | 52 | 89 | 78 | 45 | 68 |
| 67890 | A | 7/31/2025 | 89 | 26 | 78 | 35 | 36 |
| 67890 | B | 7/31/2025 | 26 | 63 | 38 | 26 | 94 |
Data above is randomized dummy data, but all data will be whole numbers.
I am trying to figure out a way to flip my metric columns into rows but am having issues figuring out a simple way to do so. I want to have a “Metric Name” column that contains the metric name and then a “This Month” and “Last Month” column so I can use those values to calculate the MoM % change.
I was looking into pivoting the table with map_agg() but that was also causing issues because the Date field is the best key I have for map_agg() and that would lead to the key being a dynamic value instead of a static value. It also didn’t give me an easy way to create that “Metric Name” column.
I’ve done this before but I cannot remember how I did it so any help is appreciated.