I have a list, masterList
, to which i want to append another lists:, contentList
and contentList2
. the content lists are the result belonging to "01-response" - the first element of the masterList
.
masterList <- list("01-response" = NULL, "02-response" = NULL,"03-response" = NULL,"04-response" = NULL,"05-response" = NULL)
contentList <- list(item1 = "text", item2 = "text2")
contentList2 <- list(item1 = "moretext", item2 = "moretext2")
I want to append contentList
and contentList2
to masterList[["01-response"]]
. However, i want all the contents to be stored inside a named list inside the masterList: `masterList[["01-response"]][["contents"]], like:
masterList
$`01-response`
$`01-response`$content
$`01-response`$content$item1
[1] "text"
$`01-response`$content$item2
[1] "text2"
$`01-response`$content$item1
[1] "moretext"
$`01-response`$content$item2
[1] "moretext2"
$`02-response`
NULL
$`03-response`
NULL
$`04-response`
NULL
$`05-response`
NULL
The problem is with the appending. I need to check if `masterList[["01-response"]][["contents"]] exists, before i append. If it exists, i simply append. If it doesnt exist, i need to create it first.
Lets specify the element as a variable, such: listElement <- "01-response"
. If i were to add a third list, contentList3 <- list(item1 = "moretext3", item2 = "moretext4")
, i would simply run:
`listElement <- "01-response"`
if(exists("content", where = masterList[[listElement]])){
masterList[[listElement]][["content"]] <- append(masterList[[listElement]][["content"]],
contentList3)
}else{
masterList[[listElement]] <- append(masterList[[listElement]],
list(content = contentList3))
}
However, this code breakes if the masterList
is empty:
masterList
$`01-response`
NULL
$`02-response`
NULL
$`03-response`
NULL
$`04-response`
NULL
$`05-response`
NULL
exists("content", where = masterList[[listElement]])
Error in as.environment(where) : using 'as.environment(NULL)' is defunct
How can i check if "content" exists at the level of masterList[[listElement]]
?
Note: this happens inside an function, threfore i want to remain flexible and avoid using masterList[["01-response"]]
. I use masterList[[listElement]]
instead, where listElement <- "01-response"