R / Excel / Tableau - 透视标题和副标题

时间:2018-05-10 19:11:46

标签: r excel tableau

我想像这样使用标题和副标题来旋转表格:

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

因此我得到了

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

我喜欢在Tableau,R或Excel中完成此操作

你可以帮我吗?

如果之前有人询问,请指导我,因为我无法找到它。

1 个答案:

答案 0 :(得分:2)

如果输入数据集采用标准格式(即唯一的列名,没有“子标题”)会更容易,但我们仍然可以使用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) 

<强>结果:

  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

数据:

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)