Member-only story

Peter’s R — transpose a tibble

Peter Hahn
2 min readFeb 20, 2022

--

Image from author

Sometimes you need to transpose a tibble, e.g. for better presentation of the data.
Assume this tibble:

df <- tibble(department = c(“hand”,”orth”,”shoulder”,”foot”),
y2018 = c(510,1200,580,610),
y2019 = c(520,1100,680,510),
y2020 = c(530,1150,610,580),
y2021 = c(580,1190,650,710))

Tibble with yearly data from departments

This tibble results from diverse filtering and counting operations. They give the sum of operations by department for the last four years. To achieve better clearness I want them with the department as columns. There is no command as „t“ for matrices which works on tibbles. We need a workaround to transpose the tibble.
We can do this using pivot_longer and pivot_wider
This a two-step procedure. Pivot_longer „lengthens“ the tibble.

df.long<- df %>% pivot_longer(cols= -1)

Instead of explicitly naming the columns I want to lengthen
pivot_longer(cols = c(y2018:y2021)) we exclude the first column : cols = -1. Details about selection of columns are available here: tidyselect

--

--

Peter Hahn
Peter Hahn

Written by Peter Hahn

Former Hand surgeon now busy with Data Science, Rstat, Machine learning, Aikido

No responses yet