我无法弄清楚为什么 R 的行为方式如下。
integerList <- list(1:10)
integerList[[1]] # this works
integerList[[1:2]] # this works BUT WHY?
integerList[[1:3]] # this fails, as I would expect
为什么
integerList[[1:2]]
工作(我认为它应该失败),但是 integerList[[1:3]]
失败(我认为应该如此)。当最后一行代码失败时,错误信息是:Error in integerList[[1:3]] : recursive indexing failed at level 2
为什么?帮助!
最佳答案
comment by 李哲源 说:
[[ 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.
取自
[[
的帮助页面.试试 ?`[[`
并向下看页面。这意味着
integerList[[1:2]]
相当于 integerList[[1]][[2]]
,返回 2
(因为它是列表第一个元素中向量的第二个元素)。显然2
没有第三个元素,所以 integerList[[1:3]]
(即 integerList[[1]][[2]][[3]]
)失败。
关于r - R : What is actually happening? 中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51529145/