嵌套列表的 R 和双括号
R and double brackets for nested lists
有很多关于索引列表的帖子,但我仍然不太了解命名和未命名嵌套列表的索引方法。这是我的例子
person <- list("name"="John","age"=19,"speaks"=c("English","French"))
Johns_brother <- list("name"="Sam","age"=20,"speaks"=c("English","Spanish"))
Johns_sister <- list("name"="Minerva","age"=17,"speaks"=c("English","Italian"))
Johns_sister <- list("name"="Minerva","age"=17,"speaks"=c("English","Italian"))
Johns_other_sister <- list("name"="Casandra","age"=23,"speaks"=c("English","Greek"))
person <- list("name"="John","age"=19,"speaks"=c("English","French"),"siblings"=list(Johns_brother,Johns_sister,Johns_other_sister))
这两种索引方法return 列出
class(person$siblings[1])
class(person$siblings[[1]])
但只有第二个允许我 select 命名元素
person$siblings[1]$name
person$siblings[[1]]$name
现在我看到了坚持(原文全部大写)的帖子"A DOUBLE BRACKET WILL NEVER RETURN A LIST. RATHER A DOUBLE BRACKET WILL RETURN ONLY A SINGLE ELEMENT FROM THE LIST"但这显然不是真的,因为两种索引方法return 都列出了。但是括号的两种形式是 returning 不同的列表,对吧?这里的底层逻辑是什么?
想一想。 [[
符号索引列表元素。但是如果那个元素本身是一个列表呢?
list(a = list(b = 1))[[1]]
# $b
# [1] 1
在上面的例子中,return值仍然是一个列表,因为a
是一个列表。值 returned 取决于被索引的值。 A DOUBLE BRACKET WILL NEVER RETURN A LIST 的说法是不正确的。
可以在 help(Extract)
-
中找到这方面的帮助
Indexing by [
is similar to atomic vectors and selects a list of the specified element(s).
Both [[
and $
select a single element of the list.
了解原子向量和递归(类列表)向量之间的区别也很有帮助。
有很多关于索引列表的帖子,但我仍然不太了解命名和未命名嵌套列表的索引方法。这是我的例子
person <- list("name"="John","age"=19,"speaks"=c("English","French"))
Johns_brother <- list("name"="Sam","age"=20,"speaks"=c("English","Spanish"))
Johns_sister <- list("name"="Minerva","age"=17,"speaks"=c("English","Italian"))
Johns_sister <- list("name"="Minerva","age"=17,"speaks"=c("English","Italian"))
Johns_other_sister <- list("name"="Casandra","age"=23,"speaks"=c("English","Greek"))
person <- list("name"="John","age"=19,"speaks"=c("English","French"),"siblings"=list(Johns_brother,Johns_sister,Johns_other_sister))
这两种索引方法return 列出
class(person$siblings[1])
class(person$siblings[[1]])
但只有第二个允许我 select 命名元素
person$siblings[1]$name
person$siblings[[1]]$name
现在我看到了坚持(原文全部大写)的帖子"A DOUBLE BRACKET WILL NEVER RETURN A LIST. RATHER A DOUBLE BRACKET WILL RETURN ONLY A SINGLE ELEMENT FROM THE LIST"但这显然不是真的,因为两种索引方法return 都列出了。但是括号的两种形式是 returning 不同的列表,对吧?这里的底层逻辑是什么?
想一想。 [[
符号索引列表元素。但是如果那个元素本身是一个列表呢?
list(a = list(b = 1))[[1]]
# $b
# [1] 1
在上面的例子中,return值仍然是一个列表,因为a
是一个列表。值 returned 取决于被索引的值。 A DOUBLE BRACKET WILL NEVER RETURN A LIST 的说法是不正确的。
可以在 help(Extract)
-
Indexing by
[
is similar to atomic vectors and selects a list of the specified element(s).Both
[[
and$
select a single element of the list.
了解原子向量和递归(类列表)向量之间的区别也很有帮助。