Search code examples
rreshape

Reshaping data frame with old variables to be new rownames


I need to reshape my data on a way that in the columns I have the values for two different years, so I can calculate the variation. The main idea is that the user can select two different years and view the variation for different KPI's.

Suppose this is my data:

df <- data.frame(
  PERIOD = c(2020, 2021),
  map = c(1, 2),
  mac = c(1, 4)
)

I would like the new data frame to have two columns (year 2020, year 2021) and "map" "mac" to be the values of a new variable called "kpi".


Solution

  • library(tidyr)
    
    pivot_longer(df, cols = -PERIOD, names_to = "kpi") |>
      pivot_wider(names_from = PERIOD, names_prefix = "year")
    

    Output

      kpi   year2020 year2021
    1 map          1        2
    2 mac          1        4