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

Convert multiple columns into wide format

I have a question regarding the best way to transform data into a wide format and hope this is asked in an understandable way. Consider the following code:

day <- c("mon", "tues", "wed", "thur")
hours <- c(2, 4, 6, 8)
cost <- c(100, 200, 300, 400)

df <- data.frame(day, hours, cost)

In this dataframe I have made, the table is in 4×3 format. I would like to transform this to 2×4 format. Consider the code below to see the format I would like to transform to:

type <- c("hours", "cost")
mon <- c(2, 100)
tues <- c(4, 200)
wed <- c(6, 300)
thur <- c(8, 400)

df1 <- data.frame(type, mon, tues, wed, thur)

I have tried using pivot wider but I am guessing I am somewhat off the mark here. Any solutions would be greatly appreciated

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

>Solution :

Try with data.table::transpose

data.table::transpose(df, make.names = 'day', keep.names = 'type')

-output

   type mon tues wed thur
1 hours   2    4   6    8
2  cost 100  200 300  400

With tidyverse, do a pivot_longer, then reshape to wide with pivot_wider

library(dplyr)
library(tidyr)
df %>% 
 pivot_longer(cols = -day, names_to = 'type') %>% 
 pivot_wider(names_from = day, values_from = value)

-output

# A tibble: 2 × 5
  type    mon  tues   wed  thur
  <chr> <dbl> <dbl> <dbl> <dbl>
1 hours     2     4     6     8
2 cost    100   200   300   400
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