Home » excel » R/Excel/Tableau – pivot title and subtitles

R/Excel/Tableau – pivot title and subtitles

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’d like to pivot a table with titles and subtitles like this:

     November November December December
Firm On-time  Not      On-time  Not
A    67%      33%      23%      77%
B    100%     0%       50%      50%
     etc etc

Thus I get

Firm Month    status  pct
A    November on-time 67%
A    November Not     33%
A    December on-time 23%
A    December Not     77%
B etc etc

I’d like this done in either Tableau, R or Excel

can you help me please?

If this has been asked before, please direct me, as I was unable to find it.

How to&Answers:

It will be much easier if the input dataset is in a standard format (i.e. unique column names, no “sub-headers”), but we can still transform it into the desire output with tools like tidyverse:

library(tidyverse)

df %>%
  rownames_to_column(var = "Firm") %>%
  gather(Month, pct, -Firm) %>%
  mutate(Month = sub('\.\d$', '', Month),
         status = ifelse(Firm == "Firm", pct, NA)) %>%
  fill(status) %>%
  filter(Firm != "Firm") %>%
  arrange(Firm) 

Result:

  Firm    Month  pct  status
1    A November  67% On-time
2    A November  33%     Not
3    A December  23% On-time
4    A December  77%     Not
5    B November 100% On-time
6    B November   0%     Not
7    B December  50% On-time
8    B December  50%     Not

Data:

df = read.table(text="     November November December December
                Firm On-time  Not      On-time  Not
                A    67%      33%      23%      77%
                B    100%     0%       50%      50%", header = TRUE, row.names = 1)