Search code examples
rlistdynamicelement

Add element to a list dynamically instead of invoking the list name directly


I have created a list using this code:

i=1
assign(paste0("dat",i,"_list"),list()) #creates empty list called dat1_list

and I would like to add a dataframe to that list, which I can do like this:

dat1_list[[1]]<-iris

HOWEVER I don't want to call the list directly by hard coding its actual name (as in the line immediately above) but instead I need to use the constituents of its name ("dat", current value of i, "_list") dynamically.

I have tried using paste0() like I did to create the list (second line of code, above), but I can't make it work.

Thank you for your time, attention and advice! Mark


Solution

  • You can do it like this but I think it's a terrible idea - this code is hard to write and hard to read.

    i=1
    obj_name = paste0("dat",i,"_list")
    
    ## initialize the empty list
    assign(obj_name,list())
    
    ## verify
    dat1_list
    # list()
    
    ## assign a value to the 1st item of the list
    assign(obj_name, `[[<-`(get(obj_name), i = 1, value = iris[1:3, ]))
    
    ## verify
    dat1_list
    # [[1]]
    #   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
    # 1          5.1         3.5          1.4         0.2  setosa
    # 2          4.9         3.0          1.4         0.2  setosa
    # 3          4.7         3.2          1.3         0.2  setosa
    
    ## extend
    assign(obj_name, `[[<-`(get(obj_name), i = 2, value = 3:5))
    
    ## verify
    # [[1]]
    #   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
    # 1          5.1         3.5          1.4         0.2  setosa
    # 2          4.9         3.0          1.4         0.2  setosa
    # 3          4.7         3.2          1.3         0.2  setosa
    # 
    # [[2]]
    # [1] 3 4 5
    

    Perhaps you'd be better using a list of lists?