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
>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