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: 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:
After binding both tibbles we use coalesce to create
Variables
column.We group by 2 rows and bring the tibble in shape with select
we use
group_modify
to add a row in first place to each groupwith a
case_when
statement we hard code the namesDoB
andEducation
.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)