Recursive Lists

Consider the following code:

b <- list(u=5,v=12) c <- list(w=13) a <- list(b,c) 

So really a list of lists. When I call a$b or a$c , why is NULL returned? Similarly, if I call a$u , a$v or a$w , NULL returned.

There is also a difference between the following:

 c(list(a=1,b=2,c=list(d=5,e=9))) 

and

 c(list(a=1,b=2,c=list(d=5,e=9)), recursive=T) 
+4
source share
2 answers

The index operator $ indexes lists by name. If you want to get the first item from an unnamed list of a , you need a[[1]] .

You can create a function that automatically adds names if they are not specified, similar to how data.frame works (this version is all or nothing), if some arguments are specified, it will not indicate the remaining, unnamed).

 nlist <- function(...) { L <- list(...) if (!is.null(names(L))) return(L) n <- lapply(match.call(),deparse)[-1] setNames(L,n) } b <- c <- d <- 1 nlist(b,c,d) nlist(d=b,b=c,c=d) 

For your second question, the answer is yes; did you try this ???

 L <- list(a=1,b=2,c=list(d=5,e=9)) str(c(L)) ## List of 3 ## $ a: num 1 ## $ b: num 2 ## $ c:List of 2 ## ..$ d: num 5 ## ..$ e: num 9 str(c(L,recursive=TRUE)) ## Named num [1:4] 1 2 5 9 ## - attr(*, "names")= chr [1:4] "a" "b" "cd" "ce" 

The first is a list that includes two numerical values ​​and a list, the second has been flattened into a named numerical vector.

+4
source

In the first part of the question, we have in the document definitions of the language R

A form using $ applies to recursive objects such as lists and pairlists. It allows only a literal string of characters or a character as an index. That is, the index is not computable: for cases where you need to evaluate the expression to find the index, use x [[expr]].

So you can change your a from a <- list(b,c) to a <- list(b=b,c=c)

  a$b = a[['b']] ## expression $u [1] 5 $v [1] 12 

In the second part of the question, you can try, for example, using the $ operator to see the difference.

 > kk <- c(list(a=1,b=2,c=list(d=5,e=9))) ## recursive objects > hh <- c(list(a=1,b=2,c=list(d=5,e=9)), recursive=T) ## atomic objects > kk$a [1] 1 > hh$a Error in hh$a : $ operator is invalid for atomic vectors 

For this reason, we get a vector from? c for hh

If recursively = TRUE, the function recursively descends through lists (and pairs) that combine all their elements into a vector.

+3
source

All Articles