6

A followup to this How to use `[[` and `$` as a function? question: I started playing a bit with the original setup (reduced the size from 10000 to 3 for simplicity)

JSON <- rep(list(x,y),3)
x <- list(a=1, b=1)
y <- list(a=1)
JSON <- rep(list(x,y),3)
sapply(JSON, "[[", "a")
[1] 1 1 1 1 1 1
sapply(JSON,"[[",'b')
[[1]]
[1] 1

[[2]]
NULL

[[3]]
[1] 1

[[4]]
NULL

[[5]]
[1] 1

[[6]]
NULL

sapply(JSON,'[[',1)
[1] 1 1 1 1 1 1
sapply(JSON,'[[',2)
Error in FUN(X[[2L]], ...) : subscript out of bounds

That I think I understand -- searching for "b" is different from demanding the existence of a second element. But then, I created a deeper list:

NOSJ<-rep(list(JSON),3)

sapply(NOSJ,'[[',1)
  [,1] [,2] [,3]
a 1    1    1   
b 1    1    1   
sapply(NOSJ,'[[',2)
$a
[1] 1

$a
[1] 1

$a
[1] 1

And now my head's hurting. Can someone expand on what [[ (or its sapply method) is doing here?

4

2 回答 2

4

您可以将 sapply 和 lapply 视为在 seq_along(NOSJ) 作为索引向量上运行的 for 循环。

 for( i in seq_along(NOSJ) NOSJ[[i]]  .... then use "[[" with the 3rd argument 

所以第一个和第二个结果是:

> NOSJ[[1]][[1]]
$a
[1] 1

$b
[1] 1

> NOSJ[[2]][[1]]
$a
[1] 1

$b
[1] 1

sapply_ lapply_ sapply_ simply2array_ 1_ 3_ 5_ 2、4 或 6 作为第三个参数不返回原子向量。我认为它应该。

于 2013-09-12T12:48:38.243 回答
3

sapply(NOSJ,'[[',1)返回from传递给[[的每个列表的第一个列表元素。尝试...sapplyNOSJ

sapply( NOSJ , length )
[1] 6 6 6

有道理吗?[[对二级列表进行操作也是如此,其第一个元素始终 包含ab因此可以强制转换为矩阵。这些 6 列表中的第二个元素始终 包含a.

于 2013-09-12T12:25:57.287 回答