How to extract the last row from list of a data frame in R?

R ProgrammingServer Side ProgrammingProgramming

Suppose we have two frames each having 5 columns that are stored in a list in R and we want to extract the last row from each data frame then we can use the lapply function. For example, if we have a list called LIST that contains the data frames described above then we can extract the last row from each data frame using the command lapply(LIST,tail,1).

Example

Consider the below list of data frames −

Live Demo

> x1<-rpois(20,5)
> x2<-rpois(20,5)
> df1<-data.frame(x1,x2)
> y1<-rnorm(20)
> y2<-rnorm(20)
> df2<-data.frame(y1,y2)
> z1<-runif(20,2,5)
> z2<-runif(20,2,5)
> df3<-data.frame(z1,z2)
> List<-list(df1,df2,df3)
> List

Output

[[1]]
   x1 x2
1   6  5
2   6  5
3   1  6
4   3  7
5   3  2
6   1  5
7   2  4
8   4  9
9   3  7
10  6  4
11  3  3
12  7  6
13  5  4
14  6  3
15  3  7
16  6  3
17  6  4
18  6  2
19  2  5
20  4  2
 
[[2]]
             y1         y2
1  -0.122804668 -1.6121924
2   0.368791187 -0.1544747
3   0.609177511 -0.1826137
4  -1.203014907  0.2230573
5   0.635002355 -1.8070089
6   1.859925346 -0.7883239
7  -0.031825058 -0.3458682
8  -2.096244574  0.9227411
9  -1.580421379  1.2784456
10  1.110385489 -0.2452274
11  0.336772170 -0.8106806
12 -0.957564919  0.3096939
13 -0.686361808 -0.9769511
14 -1.828680903 -1.3923749
15 -1.455614755  0.6422880
16  1.300948577  1.3421038
17 -0.002059289  0.3392104
18  0.577102561  0.8994493
19 -0.908456903  0.5898572
20  1.085195168  0.5538230
 
[[3]]
         z1       z2
1  2.890933 4.918197
2  3.810215 3.869794
3  4.229115 2.709872
4  2.418676 4.464096
5  3.854820 4.876632
6  4.585025 4.080327
7  2.982565 3.604979
8  3.060728 4.523820
9  3.173745 2.203814
10 2.814365 2.806997
11 3.115635 3.032836
12 3.464063 3.498520
13 4.565387 2.021247
14 3.150363 3.273335
15 3.371670 4.497002
16 3.291873 4.102787
17 2.930217 3.962004
18 4.222483 4.428542
19 4.078323 3.199733
20 2.430997 4.328706

Extracting the last row of data frames in List −

> lapply(List,tail,1)

Output

[[1]]
   x1 x2
20  4  2
 
[[2]]
         y1       y2
20 1.085195 0.553823
 
[[3]]
         z1       z2
20 2.430997 4.328706
raja
Published on 06-Mar-2021 09:42:46
Advertisements