# How to convert multiple columns into single column in an R data frame?

To convert multiple columns into single column in an R data frame, we can use unlist function. For example, if we have data frame defined as df and contains four columns then the columns of df can be converted into a single by using data.frame(x=unlist(df)).

## Example1

Live Demo

Consider the below data frame −

x1<−rpois(10,5)
x2<−rpois(10,5)
df1<−data.frame(x1,x2)
df1

## Output

x1 x2
1 2 6
2 7 3
3 6 3
4 5 7
5 4 3
6 2 6
7 7 7
8 6 2
9 2 3
10 3 10

Converting the columns in df1 to a single column −

## Example

data.frame(x=unlist(df1))

## Output

x
x11 2
x12 7
x13 6
x14 5
x15 4
x16 2
x17 7
x18 6
x19 2
x110 3
x21 6
x22 3
x23 3
x24 7
x25 3
x26 6
x27 7
x28 2
x29 3
x210 10

## Example2

Live Demo

y1<−rnorm(10)
y2<−rnorm(10)
df2<−data.frame(y1,y2)
df2

## Output

y1 y2
1 1.1017571 −1.05219232
2 −0.1452173 −0.55025708
3 0.7627143 2.39528987
4 −0.3652676 0.66343719
5 0.3079530 0.59303148
6 −0.1609029 −0.02721523
7 −0.6775391 −0.76693156
8 −0.8849706 −1.06814672
9 −2.2654645 −0.21812989
10 0.1730457 0.46043396

Converting the columns in df2 to a single column −

## Example

data.frame(y=unlist(df2))

## Output

y
y11 1.10175705
y12 −0.14521735
y13 0.76271430
y14 −0.36526756
y15 0.30795301
y16 −0.16090289
y17 −0.67753911
y18 −0.88497058
y19 −2.26546447
y110 0.17304575
y21 −1.05219232
y22 −0.55025708
y23 2.39528987
y24 0.66343719
y25 0.59303148
y26 −0.02721523
y27 −0.76693156
y28 −1.06814672
y29 −0.21812989
y210 0.46043396