rlistassignempty-list

How to create several empty lists at once?


I'd like to create 3 empty lists and assign them to different variables.

blue <- list()
green <- list()
red <- list()

Is there a possibility of a simultaneous assignment?


Solution

  • Yes, it's possible.

    red <- blue <- green <- list()
    
    ls()
    [1] "blue"  "green" "red"  
    

    Note, that the lists at first have the same memory address,

    sapply(list(red, blue, green), data.table::address)
    # [1] "0x55ee16ce46a0" "0x55ee16ce46a0" "0x55ee16ce46a0"
    

    but it will change as soon the objects are manipulated (i.e. a copy is created).

    red[[1]] <- 'foo'; blue[[1]] <- 'foo'; green[[1]] <- 'foo'
    
    sapply(list(red, blue, green), data.table::address)
    # [1] "0x55ee16f1ea48" "0x55ee16f1e930" "0x55ee16f1e818"