how are you?
I am struggling trying to reshape a data frame in R. Im working on a Shiny App and 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".
Hope you can help me,
already thank you!!
>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