3
votes

Does anyone know how to do the R equivalent of cell(2,2) in Matlab?

In Matlab, this creates a 2x2 "matrix" where each cell can be any type of data, like another matrix or something.

So basically, it can be a matrix of matrices if that's what the user wants.

Is there any way to do this in R?

1
e.g. matrix(list(matrix(NA,2,2),matrix(1,2,2),1:5,1:5),2,2), though you may not find that R is designed to be used sensibly this way, in the sense that many other R functions may not have been written with the expectation that someone would be creating matrices like this.joran

1 Answers

7
votes

You can create such an object with

mm<-matrix(list(), 2, 2)

But note that the indexing operators are a bit different. To extract/assign a single cell, you would use

mm[[1,1]]<-matrix(1:15, nrow=3)
mm[[1,2]]<-"hello"
mm[[2,1]]<-list(a=1, b=2)
mm[[2,2]]<-2

note the [[ , ]] rather than the typical [, ] for a "standard" matrix. Using only one [ , ] will return a list of the elements you request much like a standard list.

And as @joran pointed out, most functions in R are not expecting an object of this type so do not expect functions that work with matrices to automatically work with a matrix of lists like this