0

I was wondering if there is a way to switch a column under an other one using a function. Basically if I have a dataframe as follow:

a <- data.frame("A" = 1:5, "B" = 2:6) 

  A B
1 1 2
2 2 3
3 3 4
4 4 5
5 5 6

I would like to get something like:

   A
1  1
2  2
3  3
4  4
5  5
6  2
7  3
8  4
9  5
10 6
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Babas
  • 377
  • 3
  • 16

3 Answers3

2

One way you could achieve that is with stack :

a <- data.frame("A" = 1:5, "B" = 2:6) 
stack(a)

b <- stack(a)
dplyr::select(b, values)
   values
1       1
2       2
3       3
4       4
5       5
6       2
7       3
8       4
9       5
10      6

and you could of course write a shortcut function :

library(dplyr)
stack_cols <- function(df){
  stack(df) %>%
    select(values)
}

stack_cols(a)

   values
1       1
2       2
3       3
4       4
5       5
6       2
7       3
8       4
9       5
10      6
Colin FAY
  • 4,849
  • 1
  • 12
  • 29
2

You could use unlist :

DF <- data.frame(A=unlist(a))
> DF
   A
A1 1
A2 2
A3 3
A4 4
A5 5
B1 2
B2 3
B3 4
B4 5
B5 6
digEmAll
  • 56,430
  • 9
  • 115
  • 140
2

A very simple and straightforward way could be :

df <- data.frame(A=c(a$A, a$B))
> df
   A
1  1
2  2
3  3
4  4
5  5
6  2
7  3
8  4
9  5
10 6
KoenV
  • 4,113
  • 2
  • 23
  • 38