What is `` [[`looking for in this sample example?
Then follow How to use `[` and `$` as a function? question: I started playing a little with the initial setting (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 I think I understand - the search for "b" is different from the requirement for the second element to exist. 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 hurts. Can someone expand on what [[ (or his sapply method) does here?
You can think of sapply and lapply as a loop that works in seq_along (NOSJ) as an index vector.
for( i in seq_along(NOSJ) NOSJ[[i]] .... then use "[[" with the 3rd argument So, the first and second results will be as follows:
> NOSJ[[1]][[1]] $a [1] 1 $b [1] 1 > NOSJ[[2]][[1]] $a [1] 1 $b [1] 1 The difference between sapply and lapply is that sapply tries to use simply2array to return the matrix or array if the sizes of the returned values ββare the same (as in this case when using 1 , 3 or 5 as the third argument. Honestly, I donβt know why using 2,4 or 6, since the third argument does not return an atomic vector, I thought it should be.
sapply(NOSJ,'[[',1) returns the first list item of each of the lists passed to [[ on sapply from NOSJ . Try it ...
sapply( NOSJ , length ) [1] 6 6 6 Does it make sense right? Thus, [[ works on second-level lists, the first element of which always contains only a and b , so they can be copied to the matrix. The second element of these lists from 6 always contains only a .