sag
sag

Reputation: 5451

Get the last element of a matrix

Consider I have following matrix

M <- matrix(1:9, 3, 3)
M
#      [,1] [,2] [,3]
# [1,]    1    4    7
# [2,]    2    5    8
# [3,]    3    6    9

I just want to find the last element i.e M[3, 3]

As this matrix column and row size are dynamic we can't hardcode it to M[3, 3]

How can I get the value of last element?

Currently I've done using the below code

M[nrow(M), ncol(M)]
# [1] 9

Is there any better way to do it?

Upvotes: 7

Views: 8177

Answers (3)

landroni
landroni

Reputation: 2988

One way to do this and to avoid unnecessary repetition of the object name (or silly typos) would be to use pipes. Likes this:

require(magrittr)
M %>% .[nrow(.), ncol(.)]
##[1] 9
M %>% `[`(nrow(.), ncol(.))
##[1] 9
M %>% extract(nrow(.), ncol(.))
##[1] 9

The approaches are equivalent, so you can choose whichever feels more intuitive to you.

Upvotes: 0

David Arenburg
David Arenburg

Reputation: 92282

A matrix in R is just a vector with a dim attribute, so you can just subset it as one

M[length(M)]
## [1] 9

Though (as mentioned by @James) your solution could be more general in case you want to keep you matrix structure, as you can add drop = FALSE

M[nrow(M), ncol(M), drop = FALSE]
#      [,1]
# [1,]    9

Though, my solution could be also modified in a similar manner using the dim<- replacement function

`dim<-`(M[length(M)], c(1,1))
#      [,1]
# [1,]    9

Some Benchmarks (contributed by @zx8754)

M <- matrix(runif(1000000),nrow=1000)

microbenchmark(
  nrow_ncol={
    M[nrow(M),ncol(M)]
  },
  dim12={
    M[dim(M)[1],dim(M)[2]]
  },
  length1={
    M[length(M)]
  },
  tail1={
    tail(c(M),1)
  },
  times = 1000
)

# Unit: nanoseconds
#      expr     min      lq        mean    median      uq      max neval cld
# nrow_ncol     605    1209    3799.908    3623.0    6038    27167  1000   a 
#     dim12     302     605    2333.241    1811.0    3623    19922  1000   a 
#   length1       0     303    2269.564    1510.5    3925    14792  1000   a 
#    tail 1 3103005 3320034 4022028.561 3377234.0 3467487 42777080  1000   b

Upvotes: 18

Colonel Beauvel
Colonel Beauvel

Reputation: 31161

I would rather do:

tail(c(M),1)
# [1] 9

Upvotes: 2

Related Questions