How to expand a data frame rows by their index position in R?


To expand a data frame rows by its index position in R, we can follow the below steps −

  • First of all, create a data frame.
  • Then, use rep and seq_len function with nrow to expand the data frame rows by their index position.

Create the data frame

Let's create a data frame as shown below −

 Live Demo

x1<-rnorm(6)
x2<-rnorm(6)
df<-data.frame(x1,x2)
df

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

      x1          x2
1 -0.1738484 -0.5408279
2 0.5398176 0.1392769
3 0.2879338 -1.8792701
4 -1.4874235 0.6788907
5 0.9823864 0.9841566
6 -0.2491942 -1.8714372

Expand the data frame

Using rep and seq_len function with nrow to expand the rows in df by their index position −

 Live Demo

x1<-rnorm(6)
x2<-rnorm(6)
df<-data.frame(x1,x2)
df<-df[rep(seq_len(nrow(df)),1:6),]
df

Output

       x1             x2
1   -0.1738484    -0.5408279
2    0.5398176     0.1392769
2.   1 0.5398176   0.1392769
3    0.2879338    -1.8792701
3.   1 0.2879338  -1.8792701
3.   2 0.2879338  -1.8792701
4   -1.4874235     0.6788907
4.1 -1.4874235   0.6788907
4.2 -1.4874235     0.6788907
4.3 -1.4874235     0.6788907
5    0.9823864     0.9841566
5.1  0.9823864     0.9841566
5.2  0.9823864     0.9841566
5.3  0.9823864     0.9841566
5.4  0.9823864     0.9841566
6   -0.2491942    -1.8714372
6.1 -0.2491942    -1.8714372
6.2 -0.2491942    -1.8714372
6.3 -0.2491942    -1.8714372
6.4 -0.2491942    -1.8714372
6.5 -0.2491942    -1.8714372

Updated on: 14-Aug-2021

195 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements