'Combine multiple columns using dplyr in R [duplicate]

How do we combine two or more columns using dplyr?

df = data.frame(a=1:6, b=seq(2,6))

I need my output as

a 1
a 2
a 3
a 4
a 5
a 6
b 2
b 2
b 2
b 2
b 2
b 2


Solution 1:[1]

You can use pivot_longer() from the tidyr package:

library(tidyr)

df <- data.frame(a = 1:6, b = rep(2, 6))
df %>% mutate(across(.cols = everything(), .fns = as.numeric)) %>%
  pivot_longer(cols = everything(), names_to = "var", values_to = "value") %>%
  arrange(var)

Solution 2:[2]

rev(stack(df))

   ind values
1    a      1
2    a      2
3    a      3
4    a      4
5    a      5
6    a      6
7    b      2
8    b      2
9    b      2
10   b      2
11   b      2
12   b      2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 onyambu