Q:

Split row into multiple rows based on various columns

My dataframe has the following structure
x   Total   PartA   PartB
0   13      6       7
1   19      8       11
...

Now i would like to transform the dataframe into
x     Val     Colname
0     13      "Total"
0     6       "PartA"
0     7       "PartB"
1     19      "Total"
1     8       "PartA"
1     11      "PartB"

Hence, i want to transform every row into a row for each of the "Total", "PartA" and "PartB" columns. I've been searching for an elegant dplyr solution but my lack of terminology makes it hard to find any.

A:

With tidyr we can use gather. Additionally, we can use dplyr to arrange x and select the columns in a specific order, this will make the data look just like the example you've provided:
library(dplyr)
library(tidyr)

df %>% 
  gather(key = "ColName", value = "Val", -x) %>% 
  arrange(x) %>% 
  select(x, Val, ColName)

  x Val ColName
1 0  13   Total
2 0   6   PartA
3 0   7   PartB
4 1  19   Total
5 1   8   PartA
6 1  11   PartB

Data:
Lines = "x   Total   PartA   PartB
         0   13      6       7
         1   19      8       11"
df <- read.table(text = Lines, header = TRUE, stringsAsFactor = FALSE)

