Search code examples
rlistmulti-level

R - create multi-level list


Ok this is very basic, but I am trying to create a 'nested' (2-level) list in R.

I have four files referenced to like this:

files=c('path-to-file1',
        'path-to-file2',
        'path-to-file3',
        'path-to-file4') 

On the other hand, I have four different operations that I need to perform on each file:

ops=c('operation1,
       operation2,
       operation3,
       operation4')

I am doing two "for" loops (one over files and one over operations), and therefore I need to populate a two-level list that needs to be organized like this:

  - the 1st element of the first level is "file1";
    - the 1st element of the second level is "operation1"
    - the 2nd element of the second level is "operation2"
    - the 3nd element of the second level is "operation3"
    - the 4nd element of the second level is "operation4"

  - the 2nd element of the first level is "file2";
    - the 1st element of the second level is "operation1"
    - the 2nd element of the second level is "operation2"
    - the 3nd element of the second level is "operation3"
    - the 4nd element of the second level is "operation4"

  - and so on...

What is the best way to create a multi-level list like this?

EDIT: This is kind of what I am looking for:

files=c('path-to-file1',
        'path-to-file2',
        'path-to-file3',
        'path-to-file4')

ops=c('operation1,
       operation2,
       operation3,
       operation4')

# Create empty list to hold "operations" objects
list.ops = vector('list', length(ops))

# Create multi-level list lo hold both "files" and "operations" objects
multi.list = ? (how to create it? see loops below)

for (i in 1:length(files)){

  for (j in 1:length(ops)){

    (do some stuff)

    list.ops[[j]] = result of some operations

  }
    multi.list[[i]][[j]] = list.ops[[j]]
}

Solution

  • After some tests, I got what I was looking for.

    As I suspected, it was pretty simple. I just needed to create two lists with the desired sizes and populate them like in this example:

    # Define files
    files=c('path-to-file1','path-to-file2','path-to-file3','path-to-file4')
    
    # Create list to hold "files" objects
    f.list = vector('list', length(files))
    
    # Define operations
    ops=c('operation1','operation2','operation3','operation4')
    
    # Create list to hold "ops" objects
    o.list = vector('list', length(ops))
    
    # Now, iterate over files and operations    
    for (i in 1:length(files)){
    
      for (j in 1:length(ops)){
    
        (do some stuff)
    
        o.list[[j]] = result of some operations
    
      }
        f.list[[i]] = o.list
    }