Home > Enterprise >  How to bold/keep measure names in r after merging on common columns
How to bold/keep measure names in r after merging on common columns

Time:07-25

If I have two dataframes:

tibble1 <- tibble("DoB" = c("Year", "Month"),
                  "Bob" = c("2001", "3"),
                  "Kevin" = c("1999", "9"), 
                  "Stewart" = c("1868", "11"))
tibble2 <- tibble("Education" = c("School", "Degree"),
                  "Bob" = c("UNIV", "BA"),
                  "Kevin" = c("CC", "AD"), 
                  "Stewart" = c("GS", "PHD"))

And I do rbind on Bob, Steward, Kevin, how would I output a table that looks like the following: enter image description here I've tried creating rownams on the variable measures, but not sure how to retain the differing column names & bolding them.

Thanks!

CodePudding user response:

Here is a tidyverse flextable solution:

  1. After binding both tibbles we use coalesce to create Variables column.

  2. We group by 2 rows and bring the tibble in shape with select

  3. we use group_modify to add a row in first place to each group

  4. with a case_when statement we hard code the names DoB and Education.

  5. Next part is to get bold column names and row names with flextable.

library(tidyverse)
library(flextable)

bind_rows(tibble1, tibble2) %>% 
  mutate(Variables = coalesce(DoB, Education)) %>% 
  group_by(group =as.integer(gl(n(),2,n()))) %>% 
  select(Variables, Bob, Kevin, Stewart, group) %>% 
  group_modify(~ add_row(.x,.before=0)) %>% 
  mutate(Variables = case_when(is.na(Variables) & group == 1 ~ "DoB",
                               is.na(Variables) & group == 2 ~ "Education", 
                               TRUE ~ Variables)) %>% 
  ungroup() %>% 
  select(-group) %>% 
  flextable() %>% 
  bold(bold = TRUE, part = "header") %>% 
  bold(i = ~ Variables %in% c("DoB", "Education"), bold = TRUE)

enter image description here

  • Related