How to split a data frame using row number in R?

R ProgrammingServer Side ProgrammingProgramming

To split a data frame using row number, we can use split function and cumsum function. The split function will split the rows and cumsum function will select the rows. For example, if we have a data frame called df that contains twenty rows then we can split into two data frames at row 11 by using the below command −

split(df,cumsum(1:nrow(df)%in%11)).

Example

Consider the below data frame −

 Live Demo

x1<-rnorm(20,5,0.25)
x2<-rnorm(20,5,3)
x3<-rnorm(20,8,1.2)
df1<-data.frame(x1,x2,x3)
df1

Output

     x1        x2          x3
1  5.069657  10.5138048   7.468048
2  4.708780   7.4362353   5.603685
3  5.287432   5.8433927   9.552244
4  4.743582   4.4651944   9.254093
5  4.907882   4.1349492   7.590686
6  4.683656   3.7456085   7.953069
7  5.406593   1.8960190   8.760140
8  5.031933   1.4142813   8.056313
9  4.853688   3.8618121   8.469838
10 4.723343   7.4021671   7.599045
11 4.828985   5.9027257   9.756767
12 5.572417   6.6741910   6.889187
13 5.240174   8.0006150   7.333833
14 5.350764   8.1929127   7.256837
15 5.129569   7.1392279   7.453760
16 4.812799  -0.2614572   6.651369
17 4.723211  -0.2700228   5.817261
18 4.572514   1.9253317   8.074193
19 5.036176   7.5274004   8.506301
20 5.143416   1.8962568   5.950367

Splitting data frame df1 into two data frames at row number 10 −

Example

split(df1,cumsum(1:nrow(df1)%in%10))
$`0`

Output

      x1        x2          x3
1  5.069657  10.513805   7.468048
2  4.708780   7.436235   5.603685
3  5.287432   5.843393   9.552244
4  4.743582   4.465194   9.254093
5  4.907882   4.134949   7.590686
6  4.683656   3.745608   7.953069
7  5.406593   1.896019   8.760140
8  5.031933   1.414281   8.056313
9  4.853688   3.861812   8.469838
$`1`
       x1        x2         x3
10  4.723343   7.4021671  7.599045
11  4.828985   5.9027257  9.756767
12  5.572417   6.6741910  6.889187
13  5.240174   8.0006150  7.333833
14  5.350764   8.1929127  7.256837
15  5.129569   7.1392279  7.453760
16  4.812799  -0.2614572  6.651369
17  4.723211  -0.2700228  5.817261
18  4.572514   1.9253317  8.074193
19  5.036176   7.5274004  8.506301
20  5.143416   1.8962568  5.950367

Example

 Live Demo

y1<-rpois(20,5)
y2<-rpois(20,5)
y3<-rpois(20,2)
df2<-data.frame(y1,y2,y3)
df2

Output

   y1 y2 y3
1  2  5  3
2  5  5  2
3  6  6  2
4  6  6  2
5  6  4  3
6  1  5  1
7  4  4  3
8  6  4  4
9  7  5  1
10 3  6  1
11 4  4  3
12 8  7  1
13 6  3  1
14 10 2  1
15 1  3  2
16 7  4  3
17 4  2  2
18 4  2  3
19 6  6  3
20 7  3  1

Splitting data frame df1 into two data frames at row number 6 −

Example

split(df2,cumsum(1:nrow(df2)%in%6))

Output

$`0`
   y1 y2 y3
1  2  5  3
2  5  5  2
3  6  6  2
4  6  6  2
5  6  4  3
 $`1`
   y1 y2 y3
6  1  5  1
7  4  4  3
8  6  4  4
9  7  5  1
10 3  6  1
11 4  4  3
12 8  7  1
13 6  3  1
14 10 2  1
15 1  3  2
16 7  4  3
17 4  2  2
18 4  2  3
19 6  6  3
20 7  3  1
raja
Published on 16-Mar-2021 11:24:00
Advertisements