rlistfunction

How to create a function to add a list to an existing list of list?


I want to create a list of lists, and this list will be filled by calls to various functions. The output is awkward and unworkabe, so there must be a better way than the one I used. Here is a simplified code to illustrate the idea

choices <- list()

###############
add_wealth <- function(ch, wealth) {
  a <- list(type="wealth", parameter =wealth)
  list(ch, a)
}

wealth <- 1
choices <- add_wealth(choices, wealth)

##############
add_diversification <- function(ch, div) {
  a <- list(type="diversification", parameter =div)
  list(ch, a)
}

div <- .7
choices <- add_diversification(choices, div)

##############
add_margin <- function(ch, bounds) {
  a <- list(type="margin", parameter=bounds)
  list(ch, a)
}

bounds <- c(1, 3)
choices <- add_margin(choices, bounds)

choices

Ideally, here is the output I need (or something close enough)

 [[1]]
 [[1]]$type
 [1] "wealth"
 [[1]]$parameter
 [1] 1

 [[2]]
 [[2]]$type
 [1] "diversification"
 [[2]]$parameter
 [1] .7

 [[3]]
 [[3]]$type
 [1] "margin"
 [[3]]$parameter
 [1] 1 3

Solution

  • How to create a function to add a list to an existing list of list?

    If there already is an (empty) list L, i.e.,

    L = list()
    

    we can simply do

    L = append(L, list(list(type='wealth', parameter=1))) |>
      append(list(list(type='diversification', parameter=.7)))
    
    > L
    List of 2
    $ :List of 2
     ..$ type     : chr "wealth"
     ..$ parameter: num 1
    $ :List of 2
     ..$ type     : chr "diversification"
     ..$ parameter: num 0.7
    

    i.e.,

    add2list = \(l, ty, pa) append(l, list(list(type=ty, parameter=pa)))
    
    > add2list(L, "margin", c(1, 2))
    [[1]]
    [[1]]$type
    [1] "wealth"
    
    [[1]]$parameter
    [1] 1
    
    
    [[2]]
    [[2]]$type
    [1] "diversification"
    
    [[2]]$parameter
    [1] 0.7
    
    
    [[3]]
    [[3]]$type
    [1] "margin"
    
    [[3]]$parameter
    [1] 1 2