简体   繁体   中英

Appending to Nested Dictionary in R

I'm facing the issue that I cannot seem to get a dictionary created of the correct form. I want to append to a nested list element of the first so that for example I can have:

mylist[[index]] <- list("TSI" <- list(), "type"=mytype)

I'd then like to add elements to the dictionary TSI so that I have:

mylist[[index]][["TSI"]] <- list(mylist[[index]][["TSI"]], key=value)

but when I keep doing this ie

mylist[[index]][["TSI"]] <- list(mylist[[index]][["TSI"]], '2'=200)
mylist[[index]][["TSI"]] <- list(mylist[[index]][["TSI"]], '3'=300)

I find that when I do this, I don't get a list and the dictionary/list I'm trying to build is only containing one value.

As is suggested in the answer I have tried the following which is in a loop:

  # type is some kind of string i.e. "3"
  # myTSI is a value i.e. 400
  # index is a value i.e. 1
  mylist[[index]][["TSI"]] <- c(mylist[[index]][["TSI"]], type=myTSI)

index does not change for this case, but type does, so ideally should build up a series of entries in mylist[[index]][["TSI"]] where mylist[[index]][["TSI"]][["6"]] gives the myTSI for that type. However upon exiting the loop, I just get when typing:

mylist[[index]][["TSI"]] 

I get the following

type
"648746" 

but no dictionary list. Which is odd, because if I do the following in the loop:

 mylist[[index]][["TSI"]] <- c(mylist[[index]][["TSI"]], "3"=100)
 mylist[[index]][["TSI"]] <- c(mylist[[index]][["TSI"]], "4"=400)

when printing mylist[[index]][["TSI"]]

I get

3   4 
100 400 

Can't work out why this is the case.

What you are looking for is a construct like this, where l is of type list:

l = c(l, list(key=value))

This will concatinate two lists together.

R implements a copy-on-write paradigm, therefore, incrementally appending elements to a list will be extremely inefficient. Even my above suggestion is inefficient as it suffers from the same issue. The best approach is along the following lines:

tsi = lapply(some_data, some_function_to_populate_list)
mylist[[index]]$TSI = tsi

In this way you avoid copying mylist and your nested list every time you ad an element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM