How to extract the last element in an R matrix?

R ProgrammingServer Side ProgrammingProgramming

To extract the last element in an R matrix, we can use the length function along with single square brackets that are used for subsetting. For example, if we have a matrix called M as shown below −

M

1 2 3
4 5 6
7 8 9

then we can extract last value of M by using the command M[length(M)].

Example

Consider the below matrix −

 Live Demo

M1<-matrix(rpois(80,5),ncol=4)
M1

Output

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

Extracting last element in M1 −

Example

M1[length(M1)]

Output

[1] 3

Example

 Live Demo

M2<-matrix(rnorm(40),ncol=2)
M2

Output

          [,1]        [,2]
[1,]   0.15966210   0.471520825
[2,]  -0.85427581   0.488221634
[3,]  -0.61544303   0.011246667
[4,]  -1.35315700   2.143438024
[5,]   0.07160409  -0.770514833
[6,]   0.36620128   1.447494815
[7,]  -0.33961934   2.592546278
[8,]   1.16429884  -1.176167293
[9,]  -0.31079599   0.926655798
[10,] -1.38230759   0.734023448
[11,]  1.53510025  -0.004071859
[12,] -1.25239096  -1.460042884
[13,]  0.51040195   0.203301105
[14,] -0.80307697  -0.043606477
[15,]  0.14682878   0.665916402
[16,]  0.24931078  -0.770345445
[17,] -0.74226359  -0.962098594
[18,]  0.44419798  -0.178241910
[19,] -0.31078767   0.257241032
[20,]  2.13756931  -0.110932339

Extracting last element in M2 −

Example

M2[length(M2)]

Output

[1] -0.1109323

Example

 Live Demo

M3<-matrix(runif(40,2,5),ncol=2)
M3

Output

        [,1]      [,2]
[1,]  4.266885  3.616273
[2,]  2.071090  3.208100
[3,]  4.816049  4.963326
[4,]  3.531193  2.536300
[5,]  3.750360  3.664803
[6,]  4.558265  2.895776
[7,]  3.287457  2.624363
[8,]  3.879867  4.727044
[9,]  3.186532  2.490899
[10,] 2.094175  2.464493
[11,] 4.940804  2.139410
[12,] 3.283892  4.414265
[13,] 2.852312  3.089973
[14,] 2.353238  4.328873
[15,] 3.577596  2.906803
[16,] 4.052132  2.305053
[17,] 2.304785  3.232838
[18,] 3.104058  2.222455
[19,] 3.457646  3.428169
[20,] 3.869863  4.157963

Extracting last element in M3 −

Example

M3[length(M3)]

Output

[1] 4.157963
raja
Published on 16-Mar-2021 16:08:47
Advertisements