简体   繁体   中英

Matrix indexing in R

I have a matrix: ex:

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

When i access eighth element it gives me 7 like

> x[8]
  7

I want to access 8 when i type x[8] like

 > x[8]
   8

The fact is R indexes a matrix elements in top left to bottom left format but i want to index it in top left to to top right format.

How is this possible? Are there any additional arguments to use to do so?

Try this

t(x)[index]

You input is

> x = t(matrix(1:12, 4))
> x
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]    5    6    7    8
[3,]    9   10   11   12

You can get

> t(x)[1]
[1] 1
> t(x)[8]
[1] 8
> t(x)[12]
[1] 12

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM