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

How can I subset a list in R according to an index?

If I have a list in R:

list_test = list()
list_test[[1]] = 1
list_test[[2]] = 2

And I have an index

index_test = c(1,2)

How can I run list_test[[index_test]] to return a vector with 1 2? When I try to run this command I get the error:

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

Error in list_test[[index_test]] : subscript out of bounds

>Solution :

The [[ in your case can only accept a length-1 vector (there are alternatives when list_test is nested, yours is not). I think you want unlist(list_test[index_test]).

list_test = list()
list_test[[1]] = 1
list_test[[2]] = 2
index_test = c(1,2)
unlist(list_test[index_test])
# [1] 1 2

Refs:

The expression quux[[c(1, 2)]] is equivalent to quux[[1]][[2]]. This is discussed in ?[[ as:

     ‘[[’ can be applied recursively to lists, so that if the single
     index ‘i’ is a vector of length ‘p’, ‘alist[[i]]’ is equivalent to
     ‘alist[[i1]]...[[ip]]’ providing all but the final indexing
     results in a list.

For example,

quux <- list(1:3, 4:7)
str(quux)
# List of 2
#  $ : int [1:3] 1 2 3
#  $ : int [1:4] 4 5 6 7
quux[[c(1, 2)]]
# [1] 2

A deeper-nested option:

quux <- list(list(1:3, 4:6), list(7:9, 10:13))
str(quux)
# List of 2
#  $ :List of 2
#   ..$ : int [1:3] 1 2 3
#   ..$ : int [1:3] 4 5 6
#  $ :List of 2
#   ..$ : int [1:3] 7 8 9
#   ..$ : int [1:4] 10 11 12 13
quux[[c(1,2,3)]]
# [1] 6
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