How to extract the first row of each matrix stored in a list in R?

R ProgrammingServer Side ProgrammingProgramming

To extract the first row of each matrix stored in a list in R, we can use lapply function. For example, if we have a list called LIST that contains some matrices then we can find the first row of each matrix by using the command given below −

lapply(LIST,'[',1,)

Check out the below given example to understand how it can be done.

Example

Following snippet creates a list of matrices −

M1<-matrix(rpois(20,5),ncol=2)
M2<-matrix(rpois(20,1),ncol=2)
M3<-matrix(rpois(20,8),ncol=2)
M4<-matrix(rpois(20,10),ncol=2)
List<-list(M1,M2,M3,M4)
List

The following list of matrices are created −

[[1]]
    [,1][,2]
[1,]  2  6
[2,]  6  6
[3,] 10  5
[4,]  3  1
[5,]  6  7
[6,]  7  2
[7,]  6  5
[8,]  4  6
[9,]  9  7
[10,] 7  6

[[2]]
    [,1][,2]
[1,]  1  1
[2,]  1  0
[3,]  1  3
[4,]  2  1
[5,]  1  1
[6,]  5  0
[7,]  2  0
[8,]  0  0
[9,]  2  0
[10,] 1  0

[[3]]
     [,1] [,2]
[1,]  13    7
[2,]   9   11
[3,]  11   12
[4,]  10    3
[5,]   8   10
[6,]   9    4
[7,]   6    8
[8,]  13    8
[9,]  13    8
[10,]  5    6

[[4]]
     [,1] [,2]
[1,]   7    8
[2,]  10   16
[3,]  11   14
[4,]   6   10
[5,]  10   12
[6,]   7    7
[7,]  13    8
[8,]  14    6
[9,]   9   14
[10,] 12   18

Now, in order to extract the first row of each matrix in List, add the following code to the above snippet −

M1<-matrix(rpois(20,5),ncol=2)
M2<-matrix(rpois(20,1),ncol=2)
M3<-matrix(rpois(20,8),ncol=2)
M4<-matrix(rpois(20,10),ncol=2)
List<-list(M1,M2,M3,M4)
lapply(List,'[',1,)

Output

If you execute all the above given snippets as a single program, it generates the following output−

[[1]]
[1] 2 6

[[2]]
[1] 1 1

[[3]]
[1] 13 7

[[4]]
[1] 7 8
raja
Updated on 11-Nov-2021 05:15:43

Advertisements