R - 创建多级列表

时间:2017-01-23 07:20:56

标签: r list multi-level

好的,这是非常基本的,但我正在尝试创建一个嵌套的' R(

)中的(2级)列表

我有四个文件引用如下:

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

另一方面,我需要对每个文件执行四种不同的操作:

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

我正在做两个"因为"循环(一个在文件上,一个在操作上),因此我需要填充一个需要按如下方式组织的两级列表:

  - 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...

创建像这样的多级列表的最佳方法是什么?

编辑:这就是我要找的东西:

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]]
}

1 个答案:

答案 0 :(得分:1)

经过一些测试,我得到了我想要的东西。

我怀疑,这很简单。我只需要创建两个具有所需大小的列表并填充它们,如下例所示:

# 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
}