2

I have a nested named list in R and given a name, I want to check whether that's present in the names of that nested list.

For level 1 depth, given_name %in% names(list) is working fine. But how to search for names at different levels.

For ex: list (a:1, b:1, c:( c_a:2,c_b:3 )). How to check whether c$c_a is in the list.

1 Answer 1

2

I. Creating Nested List

  Your_list <- list(a=list(x=c(4,5)),b=list(c=list(y=c(8,99)),d=c("a","b")))

  names(Your_list)
  # [1] "a" "b"

  names(.Internal(unlist(Your_list, TRUE, TRUE)))
  # [1] "a.x1"   "a.x2"   "b.c.y1" "b.c.y2" "b.d1"   "b.d2" 

  str(Your_list)
  # List of 2
  #  $ a:List of 1
  #   ..$ x: num [1:2] 4 5
  #  $ b:List of 2
  #   ..$ c:List of 1
  #   .. ..$ y: num [1:2] 8 99
  #   ..$ d: chr [1:2] "a" "b"

II. Removing Nesting from the list

  New_list <- unlist(Your_list)
  New_list
  #   a.x1   a.x2 b.c.y1 b.c.y2   b.d1   b.d2 
  #    "4"    "5"    "8"   "99"    "a"    "b" 

  class(New_list)
  # [1] "character"

  str(New_list)
  #  Named chr [1:6] "4" "5" "8" "99" "a" "b"
  #  - attr(*, "names")= chr [1:6] "a.x1" "a.x2" "b.c.y1" "b.c.y2" ...

III. Converting it to list without nesting

  New_list <- as.list(New_list)
  New_list
  # $a.x1
  # [1] "4"

  # $a.x2
  # [1] "5"

  # $b.c.y1
  # [1] "8"

  # $b.c.y2
  # [1] "99"

  # $b.d1
  # [1] "a"

  # $b.d2
  # [1] "b"

  class(New_list)
  # [1] "list"

  str(New_list)
  # List of 6
  #  $ a.x1  : chr "4"
  #  $ a.x2  : chr "5"
  #  $ b.c.y1: chr "8"
  #  $ b.c.y2: chr "99"
  #  $ b.d1  : chr "a"
  #  $ b.d2  : chr "b"

IV. Accessing elements from Flat list New_list by names

  New_list$a.x1
  # [1] "4"
  New_list$a.x2
  # [1] "5"
  New_list$b.d2
  # [1] "b"
  New_list$b.c.y2
  # [1] "99"

Note: Here, the class is not preserved for the elements of flatten list. You will need to preserve the class when unlisting the list.

As you see all of them are character at the end.

Sign up to request clarification or add additional context in comments.

9 Comments

Yeah, that worked. Thanks Can u xplain what .Internal is doing there ? names(unlist(list, True, True)) does the same.
Why did u use .Internal ? Just names(unlist(list, True, True)) also does the same.
I have just started doing all this it is really core. For the start you can type ?.Internal, besides this there are many other functions for R core developers
One more thing, Can I make a nested named list into a named list of just level 1 by keeping the names same ?
So for the list I mentioned in my question, I want to convert it into : (a:1, b:1 , c.c_a:2, c.c_b:3) . I basically want to remove nesting
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.