如果我有一个用R表示的列表:
list_test = list()
list_test[[1]] = 1
list_test[[2]] = 2
我有一个索引
index_test = c(1,2)
我如何运行list_test[[index_test]]
才能返回一个有12的向量?当我try 运行此命令时,我收到错误:
Error in list_test[[index_test]] : subscript out of bounds
如果我有一个用R表示的列表:
list_test = list()
list_test[[1]] = 1
list_test[[2]] = 2
我有一个索引
index_test = c(1,2)
我如何运行list_test[[index_test]]
才能返回一个有12的向量?当我try 运行此命令时,我收到错误:
Error in list_test[[index_test]] : subscript out of bounds
在您的情况下,[[
只能接受长度为1的向量(当list_test
是nested时,还有其他 Select ,而您的不是).我想你要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
回头见:
?[[
(又名?Extract
和?[
).表达式quux[[c(1, 2)]]
相当于quux[[1]][[2]]
.这在?[[
中讨论为:
‘[[’ 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.
例如,
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
quux[[1]][[2]] ## same thing
嵌套更深的选项:
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
quux[[1]][[2]][[3]] ## same thing