Home > Net >  how to put a column below another
how to put a column below another

Time:05-09

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!

CodePudding user response:

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))

CodePudding user response:

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
  •  Tags:  
  • r
  • Related