Pubblicato il in English | 0 commenti

Matlab cell arrays equivalent in R

If you are moving from Matlab to a R environment, probably you would like to keep using cell arrays to save different types of data.

While this in Matlab is pretty easy with the instruction “cell(n.row, n.column)”, in R it can be more complex.

There is, for example, the instruction data.frame(), but it forces you to have the same number of elements in each field. So, we are going to cover today three different solutions, based on different use of R lists.

Concatenate different elements using lists

The first solution is really similar to the use of cell arrays in Matlab.
We are creating a list with a matrix, a string and a vector:

my.list <- list(matrix(nrow=5, ncol=2), "hello", c(10,8,7,3))

But this time, in order to access each element you need to use the double square brackets. For example, if I want to extract the number 8 from my.list:

my.list[]

Create a matrix from a list

Now suppose that you have a function which is invoked multiple times. That function (we’ll call it my.list) returns a list of three elements, and you want to save the last one, for example a vector of four elements. You can achieve this result with this simple for cicle:

my.matrix<-matrix(nrow=12, ncol=4) #create a matrix

for (i in (1:dim(my.matrix))){
save.me <- my.function(par) #save the list from the function
my.matrix[i,]<-save.me[] } #save the vector, last element of the list, in a matrix

Use a matrix of lists

The last case we are covering today is the creation of a matrix of lists.
Each element of my.matrix is a list, so we save different data in different positions

my.matrix<-matrix(list(), 2, 2)
my.matrix[[1,1]]<-matrix(nrow=5, ncol=2)
my.matrix[[1,2]]<-"hello"
my.matrix[[2,1]]<-c(10,8,7,3)
my.matrix[[2,2]]<-list(a=1, b=2)

If again I want to access the number 8 in the vector, I have to use the double square bracket notation:

my.matrix[[2,1]]