Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Sub Headers in R

Tags:

r

I'd like to create a df that has a header and a subheader. Example below:

I want to take the following input:

input <- tibble::tribble(
             ~Region,  ~Day_1, ~Day_2,  ~Day_3,
           "Central",  "Boat",     NA,      NA,
           "Central",      NA, "Shoe",      NA,
           "Central",      NA,     NA, "Table",
           "Pacific",      NA, "Boat",      NA,
           "Pacific", "Table",     NA,      NA,
           "Pacific",      NA,     NA,  "Shoe",
           "Eastern",  "Boat",     NA,      NA,
           "Eastern",      NA, "Shoe",      NA,
           "Eastern",      NA,     NA, "Table",
           "Eastern", "Watch",     NA,      NA,
           "Eastern", "Chair",     NA,      NA,
           "Eastern",      NA,  "Cup",      NA
           )

and convert it to the following output:

  Central Central Central Pacific Pacific Pacific Eastern Eastern Eastern
  <chr>   <chr>   <chr>   <chr>   <chr>   <chr>   <chr>   <chr>   <chr>  
1 Day_1   Day_2   Day_3   Day_1   Day_2   Day_3   Day_1   Day_2   Day_3  
2 Boat    Shoe    Table   Table   Boat    Shoe    Boat    Shoe    Table  
3 NA      NA      NA      NA      NA      NA      Watch   Cup     NA     
4 NA      NA      NA      NA      NA      NA      Chair   NA      NA 

Any thoughts? Thank you in advance!

like image 986
sschade Avatar asked Nov 20 '25 12:11

sschade


1 Answers

library(tidyverse)

input %>%
  pivot_longer(-Region) %>%
  na.omit() %>%
  group_by(Region, name) %>%
  mutate(id = row_number()) %>%
  pivot_wider(names_from = id, values_from = value) %>%
  data.table::transpose(make.names = TRUE)
  
  Central Central Central Pacific Pacific Pacific Eastern Eastern Eastern
1   Day_1   Day_2   Day_3   Day_2   Day_1   Day_3   Day_1   Day_2   Day_3
2    Boat    Shoe   Table    Boat   Table    Shoe    Boat    Shoe   Table
3    <NA>    <NA>    <NA>    <NA>    <NA>    <NA>   Watch     Cup    <NA>
4    <NA>    <NA>    <NA>    <NA>    <NA>    <NA>   Chair    <NA>    <NA>
like image 109
KU99 Avatar answered Nov 23 '25 02:11

KU99