How to stack multiple columns into one using R

Viewed 201

I have the following data frame:

A <- c(3,5,6,7)
B <- c(2,4,5,3)
C <- c(4,6,7,8)
D <- c(2,4,5,3)
gene <- c(1,2,3,4)
df <- data.frame(gene,A,B,C,D)
df
  gene A B C D
1    1 3 2 4 2
2    2 5 4 6 4
3    3 6 5 7 5
4    4 7 3 8 3

How can I stack each lettered column into one new column called "count" such that there is another new column called "sample" that keeps track of the original column from which each count value came frame (ie. I would like the following output):

count sample
  3     A  
  5     A
  6     A
  7     A
  2     B
  4     B
  5     B
  3     B
  4     C
  6     C
  7     C
  8     C
  2     D
  4     D
  5     D
  3     D

Sorry this is difficult to explain but the output data frame above should make it clear.

Thanks

2 Answers

In base R, use stack after removing the first column

out <- stack(df[-1])
names(out) <- c("count", "sample")

We could use pivot_longer:

library(tidyr)
library(dplyr)
df %>% 
  pivot_longer(
    cols = -gene,
    names_to = "sample",
    values_to = "count"
  ) %>% 
  select(-gene) %>% 
  arrange(sample)
   sample count
   <chr>  <dbl>
 1 A          3
 2 A          5
 3 A          6
 4 A          7
 5 B          2
 6 B          4
 7 B          5
 8 B          3
 9 C          4
10 C          6
11 C          7
12 C          8
13 D          2
14 D          4
15 D          5
16 D          3
Related