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:
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:
?[[(aka?Extractand?[).- The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe
- Dynamically select data frame columns using $ and a character value
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