PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 2, 2022

[FIXED] How to bold/keep measure names in r after merging on common columns

 August 02, 2022     format, html, html-table, r, r-markdown     No comments   

Issue

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!


Solution

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



Answered By - TarJae
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing