1

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
camille
  • 16,432
  • 18
  • 38
  • 60
Rasin Rs
  • 11
  • 1

2 Answers2

0

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)
  • Why are you trying to convert columns to numeric when they already are? – camille Jan 24 '22 at 18:54
  • Yes your right both columns are already numeric and so you don't need to do the conversion. Sorry for the redundant code. However, if you have many columns to combine, then I think it might be safer to run that line to avoid potential errors! – Gen-Chang Hsu Jan 25 '22 at 04:39
0
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
Onyambu
  • 67,392
  • 3
  • 24
  • 53