bfoste01
bfoste01

Reputation: 359

Tidy combine columns or rows simultaneously apply formats

Context: I'm working on building some functions that automate table generation and styling for report generation (i.e., late-stage analytic work). The approach I'm taking is to wrangle my data into data frames that I will feed to 'flextable' for further processing. At various points in the workflow, I need to collapse rows or columns and apply some formatting.

In the example code below you will find two data frames, long_df and wide_df, I'd like to get these to look like respective target data frames. I'm stuck on the approach.

I thought maybe 'tidyr::unite' or using paste in 'dplyr::mutate' when in long form. Any tips would be appreciated.

library(tibble)

long_df <- tribble(
  ~Statistc, ~Model_1, ~Model_2,
  'G2',       413.42,  532.93,
  'df',       2,       3,
  'CFI',      .95,     .91,
)


wide_df <- tribble(
  ~model,     ~G2,     ~df,  ~CFI,
  'Model_1',  413.42,  2,   .95, 
  'Model_2',  532.93,  3,   .91, 
)


target_wide_df <- tribble(
  ~model,   ~'G2 (df)',    ~CFI,
  'Model_1',  '413.42 (2)',  .95, 
  'Model_2',  '532.93 (3)',  .91, 
)

target_long_df <- tribble(
  ~Statistc,   ~Model_1,    ~Model_2,
  'G2 (df)',   '413.42 (2)',  '532.93 (3)',
  'CFI',      .95,          .91,
)

Upvotes: 1

Views: 59

Answers (1)

akrun
akrun

Reputation: 887851

From 'long_df', we can do

library(tidyverse)
long_df %>%
    group_by(grp = rep(1:2, 2:1)) %>% 
    summarise_all(list(~ if(n() > 1) str_c(.[1], ' (', .[2], ')') 
          else as.character(.))) %>%
    ungroup %>%
    select(-grp)

From wide_df, a similar approach with str_c or str_c +unite can be tried

wide_df %>%
     unite(`G2 (df)`, G2, df, sep=" (") %>% 
     mutate(`G2 (df)` = str_c(`G2 (df)`, ')')) 

Upvotes: 1

Related Questions