rmarkdown::render_site()


Goal: Convert data format from long to wide

There are times when one wants to widen/spread a column i,e., convert a column to have its unique values as separate columns, hence making the data format long to wide. One can easily achieve this by using the pivot_wider function from the tidyr package. Let me walk you through with an example:

library(tidyr)

metric1 <- c(15.3, 14.7, 15.2, 13.8, 15.4, 14.8, 14.9, 15.1, 15.9)
id <- c("A01", "A01", "A01", "B01", "B01", "B01", "B02", "B02", "B02")
date <- as.Date(rep(c("2022-01-01", "2022-01-02", "2022-01-03"), 3))

df <- data.frame(metric1, id, date)

df_spread <- df %>% tidyr::pivot_wider(names_from = date, values_from = metric1)
# Before piot_wider()
knitr::kable(df, align = "c", caption = "<center>Table 1</center>") %>% 
  kableExtra::kable_styling(position = "center", full_width = F) 
Table 1
metric1 id date
15.3 A01 2022-01-01
14.7 A01 2022-01-02
15.2 A01 2022-01-03
13.8 B01 2022-01-01
15.4 B01 2022-01-02
14.8 B01 2022-01-03
14.9 B02 2022-01-01
15.1 B02 2022-01-02
15.9 B02 2022-01-03
# After piot_wider()
knitr::kable(df_spread, align = "c", caption = "<center>Table 2</center>") %>% 
  kableExtra::kable_styling(position = "center", full_width = F) 
Table 2
id 2022-01-01 2022-01-02 2022-01-03
A01 15.3 14.7 15.2
B01 13.8 15.4 14.8
B02 14.9 15.1 15.9