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?