如果我有一个用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_testnested时,还有其他 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

回头见:

表达式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

R相关问答推荐

列出用m n个值替换来绘制n个数字的所有方法(i.o.w.:R中大小为n的集合的所有划分为m个不同子集)

基于shiny 应用程序中的日期范围子集xts索引

在R中查找每个组不同时间段的总天数

如何修复R码的置换部分?

任意列的欧几里得距离

如何改变时间图R中的悬停信息?

单个轮廓重叠条的单独图例

非线性混合效应模型(NLME)预测变量的置信区间

合并DFS列表并将索引提取为新列

使用R中的正则表达式将一列分割为多列

使用`Watch()`和`renderUI()`时,不再满足仍出现在SHILINY AFTER条件中的条件输入

跨列查找多个时间报告

从多面条形图中删除可变部分

当每个变量值只能 Select 一次时,如何从数据框中 Select 两个变量的组合?

为什么我对圆周率图的蒙特卡罗估计是空的?

使用其他DF中的文件名将列表中的每个元素保存到文件中

如果y中存在x中的值,则将y行中的多个值复制到相应的x行中

通过分析特定列中的字符串在数据框中创建新的行和列

如何在R曲线图弹出窗口中更改r和theta标签

如何使用包含要子集的值的列表或数据框来子集多个列?