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

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
Updated on: 2026-03-11T22:50:55+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements