Search code examples
rmatlablistcelltransfer

how to create two-dimension list in R


I want to transfer matlab code into R, ctlist is a vector, matlab code as folllowed:

telist{i,j}=ctlist;
[value,number]=max(ctlist);

I just wonder there is "data structure" in R like the telist{i,j} in matlab


Solution

  • You can have infinitely nested lists:

    list1 <- list()
    
    list1[[1]] <- list()
    
    list[[1]][[1]] <- list()
    

    and so on...

    But for a more practical example, say you want 2 lists having each 3 lists inside:

    my.list.1 <- list()
    my.list.1[[1]] <- list()
    my.list.1[[2]] <- list()
    my.list.1[[3]] <- list()
    
    my.list.2 <- list()
    my.list.2[[1]] <- list()
    my.list.2[[2]] <- list()
    my.list.2[[3]] <- list()
    

    Is there a specific syntax to create those list structures in no time?

    As per Richard Skriven's comment, replicate can do that. Example: my.lists <- replicate(n=5, expr=list()) will create 5 lists all at once and store them under the name my.lists.

    Filling in the lists

    You could indeed fill in any of those lists or sub-lists with vectors or matrices or arrays. For instance:

    my.list.1[[1]][[1]] <- c(1,5,3,3,5,3)
    my.list.1[[1]][[2]] <- matrix(0, nrow=10, ncol=10)
    

    There are no constraints, really.

    Dynamically extending lists

    You could also add dynamically elements to your lists, in loops for instance:

    my.list <- list() # we're creating a new one, but the following loop could
                      # be using a pre-existing list with data already inside
    for(i in 1:10) {
      my.list[[length(my.list) + 1]] <- (i*1):(i*200)
    }
    

    Arrays

    If however all your data are all of the same type structured in "rectangular/cubic" ways, you can use multidimensional arrays.

    > array(data = NA, dim = c(3,3,3))
    , , 1
    
         [,1] [,2] [,3]
    [1,]   NA   NA   NA
    [2,]   NA   NA   NA
    [3,]   NA   NA   NA
    
    , , 2
    
         [,1] [,2] [,3]
    [1,]   NA   NA   NA
    [2,]   NA   NA   NA
    [3,]   NA   NA   NA
    
    , , 3
    
         [,1] [,2] [,3]
    [1,]   NA   NA   NA
    [2,]   NA   NA   NA
    [3,]   NA   NA   NA