How to unsplit a split in R data frame?



To unsplit a split in R data frame, we can follow the below steps −

  • First of all, create a data frame.

  • Then, use split function to split the data frame.

  • After that, use do.call function along with rbind function unsplit the data frame.

Example

Create the data frame

Let’s create a data frame as shown below −

x<-rpois(25,5) y<-rpois(25,5) z<-rpois(25,5) df<-data.frame(x,y,z) df

Output

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

 x y z 1 4 3 3 2 5 2 3 3 5 6 3 4 9 2 5 5 8 5 5 6 3 6 5 7 6 3 4 8 2 2 5 9 2 6 4 10 6 6 4 11 2 9 5 12 4 11 4 13 5 3 5 14 6 4 6 15 3 6 4 16 4 6 5 17 6 2 8 18 3 6 5 19 5 7 6 20 2 5 3 21 3 8 5 22 7 5 6 23 1 6 3 24 7 3 6 25 4 3 5

Split the data frame

Using split function to split the data frame −

x<-rpois(25,5) y<-rpois(25,5) z<-rpois(25,5) df<-data.frame(x,y,z) new_df<-split(df,df$x) new_df

Output

$ `2`    x y z 12 2 4 6 $`3`    x y z 14 3 6 4 15 3 5 5 21 3 6 5 $`4`     x  y z  2  4 10 6  4  4  7 3  7  4  7 7  8  4  2 3 11  4  4 4 13  4  3 4 16  4  3 4 19  4  2 2 23  4  3 6 $`5` x y z 1 5 3 4 25 5 9 3 $`6` x y z 5 6 7 0 6 6 1 8 $`7` x y z 3 7 7 1 9 7 3 0 18 7 2 4 22 7 9 4 24 7 9 2 $`8` x y z 10 8 3 4 $`9` x y z 20 9 2 2 $`10` x y z 17 10 7 9

Unsplit the data frame

Using do.call function along with rbind function unsplit the data frame df −

x<-rpois(25,5) y<-rpois(25,5) z<-rpois(25,5) df<-data.frame(x,y,z) new_df<-split(df,df$x) do.call("rbind",new_df)

Output

      x y z 2.13  2 7 6 2.24  2 9 5 3.5   3 2 5 3.9 3 7 2 3.11  3 3 2 3.19  3 3 8 3.20  3 5 3 4.2   4 2 4 4.3   4 3 6 4.4   4 4 1 4.25  4 8 6 5.7   5 2 5 5.8   5 4 8 5.14  5 4 5 5.15  5 4 4 5.21  5 9 2 6.1   6 8 5 6.17  6 6 5 6.18  6 2 4 7 7 8 3 8.10  8 5 4 8.16  8 6 6 9.12  9 3 4 9.22  9 4 6 9.23  9 8 5
Updated on: 2021-11-11T05:44:11+05:30

891 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements