How to combine multiple columns into one in R data frame without using column names?



To combine multiple columns into one in R data frame without using column names, we can follow the below steps −

  • First of all, create a data frame.
  • Then, convert the data frame into a single column data frame.
  • Again, convert the data frame into a single column without column names displayed in rows using row.names function.

Create the data frame

Let's create a data frame as shown below −

Example

 Live Demo

x<-sample(1:50,5) y<-sample(1:50,5) z<-sample(1:50,5) a<-sample(1:50,5) b<-sample(1:50,5) c<-sample(1:50,5) df<-data.frame(x,y,z,a,b,c) df

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

Output

  x  y z  a  b  c 1 48 6 8 48 49 22 2 7 34 48 28 17 17 3 25 40 1 22 12 29 4 38 21 27 33 8 5 5 5 20 7 50 46 32

Convert the data frame into a single column data frame

Using unlist function to convert df into a single data frame −

Example

 Live Demo

x<-sample(1:50,5) y<-sample(1:50,5) z<-sample(1:50,5) a<-sample(1:50,5) b<-sample(1:50,5) c<-sample(1:50,5) df<-data.frame(x,y,z,a,b,c) data.frame(unlist(df))

Output

unlist.df. x1 48 x2 7 x3 25 x4 38 x5 5 y1 6 y2 34 y3 40 y4 21 y5 20 z1 8 z2 48 z3 1 z4 27 z5 7 a1 48 a2 28 a3 22 a4 33 a5 50 b1 49 b2 17 b3 12 b4 8 b5 46 c1 22 c2 17 c3 29 c4 5 c5 32

Convert the data frame into a single column data frame without column names

Using unlist function to convert df into a single data frame without row numbers represented by column names −

Example

 Live Demo

x<-sample(1:50,5) y<-sample(1:50,5) z<-sample(1:50,5) a<-sample(1:50,5) b<-sample(1:50,5) c<-sample(1:50,5) df<-data.frame(x,y,z,a,b,c) data.frame(One=unlist(df,use.names=FALSE))

Output

 One 1 48 2 7 3 25 4 38 5 5 6 6 7 34 8 40 9 21 10 20 11 8 12 48 13 1 14 27 15 7 16 48 17 28 18 22 19 33 20 50 21 49 22 17 23 12 24 8 25 46 26 22 27 17 28 29 29 5 30 32
Updated on: 2021-08-10T09:26:48+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements