Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reshaping data frame with old variables to be new rownames tidyverse

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading