Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Access an element of a list in the same manner how you access an element of a matrix

I have a matrix:

mat <- matrix(c(3,9,5,1,-2,8), nrow = 2)

     [,1] [,2] [,3]
[1,]    3    5   -2
[2,]    9    1    8

I have a list:

lst <- as.list(data.frame(matrix(c(3,9,5,1,-2,8), nrow = 2)))

$X1
[1] 3 9

$X2
[1] 5 1

$X3
[1] -2  8

I can access my matrix by mat[i,j]
I can access my list lst[[c(i,j)]]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But if in a matrix if I do mat[1,2] I get a 5. If I use same numbers in a list lst[[c(1,2)]] I get 9.

Is there a way I can get the same numbers when I access a list? Maybe manipulate the list in certain manner? When I use lst[[c(1,2)]] I want to get 5 instead of 9.I want to get the same numbers I get when using mat[i,j].

>Solution :

You can use transpose() from purrr to transpose a list.

lst2 <- purrr::transpose(lst)

lst2[[c(1,2)]]
# [1] 5
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading