Assign to Sublist

I have two api calls that are identical except the depth of the json/list file. The goal is to be able to assign directly to a sublist without having to add if else statements all around my code. Here is an example,

# Api call 1
body <- list(
    config = list(
        name = "John",
        age = 21

# Api call 2
body <- list(
    name = "John",
    age = 21

Since the parameters that are passed to the body variable are many, I don't want to add an if else statement for each. The following example is not desired.

if (api == "api_1") body[['config']][['name']] <- 'John' else body[['name']] <- 'John'
if (api == "api_1") body[['config']][['age']] <- 21 else body[['age']] <- 21

What I would prefer to do is to assign the sublist directly to a variable so that I would have to call only one if statement for all the cases. For example,

if (api == "api_1"){
    temp_var <- vector("list", length = 1)
    names(temp_var) <- "config"
    body <- temp$config
} else {
   body <- list()

However, my implementation does not work because it directly assigns name to a new list within the body variable. To illustrate,

body[["name"]] <- "John" 
# returns list(name = "John") for the first case too.

My question is how to assign a sublist in such a way that all my future assignments to that variable will be assigned to the sublist?

If you want to work with lists or sublists I would definitely recommend you look at purrr. It is one of the best libraries if you want to have a really convenient way to manipulate any set of nested lists. Have a look here: and here: cheatsheets/purrr.pdf at main · rstudio/cheatsheets · GitHub

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.