'how to put a column below another

I would like to put the columns of a dataframe one below the other.

I have this:

a <- c(1, 2, 3, 4)
b <- c(5, 6, 7, 8)
c <- c(9, 10, 11, 12)
abc <- data.frame(a, b, c)

I would like to end up having this:

abc <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)

Note that in my original dataset I have multiple columns, so I would like to obtain a code without mentioning specific columns.

Thanks!

r


Solution 1:[1]

base R

stack(abc)
#    values ind
# 1       1   a
# 2       2   a
# 3       3   a
# 4       4   a
# 5       5   b
# 6       6   b
# 7       7   b
# 8       8   b
# 9       9   c
# 10     10   c
# 11     11   c
# 12     12   c

Data

abc <- structure(list(a = c(1, 2, 3, 4), b = c(5, 6, 7, 8), c = c(9, 10, 11, 12)), class = "data.frame", row.names = c(NA, -4L))

Solution 2:[2]

Another possible solution, in base R:

a <- c(1, 2, 3, 4)
b <- c(5, 6, 7, 8)
c <- c(9, 10, 11, 12)
abc <- data.frame(a, b, c)

data.frame(values = unlist(abc))

#>    values
#> a1      1
#> a2      2
#> a3      3
#> a4      4
#> b1      5
#> b2      6
#> b3      7
#> b4      8
#> c1      9
#> c2     10
#> c3     11
#> c4     12

Solution 3:[3]

unlist() is really all you need.

df <- as.data.frame(matrix(1:9, ncol=3))
v <- as.vector(unlist(df))
> df
  V1 V2 V3
1  1  4  7
2  2  5  8
3  3  6  9
> v
[1] 1 2 3 4 5 6 7 8 9
> unlist(df)
V11 V12 V13 V21 V22 V23 V31 V32 V33 
  1   2   3   4   5   6   7   8   9 

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 r2evans
Solution 2 PaulS
Solution 3 Fujibayashi Kyou