0

Occasionally, I've written buggy R code that produced an object that printed like a matrix, but where the elements were vectors. It might look something like this:

 [,1] [,2] [,3] [1,] character,2 character,2 character,2 [2,] character,2 character,2 character,2 [3,] character,2 character,2 character,2 

I've never intended to create one before, but now I'm working on a project where this data structure could be useful.

What is it? How do I make one? What are its properties? For iterating over rows and columns, how does its efficiency compare to a nested list, an array, or a list of matrices?

5
  • It's a matrix of lists. To make one, you can do matrix(list(c("a", "b"))) for example Commented Mar 18, 2015 at 19:24
  • @RichardScriven so it's just a list with a .Dim attribute? That's my impression based on dput(matrix(list(c("a", "b")))). This is really cool and I wonder why nobody does it. At any rate you should post that as an answer. Commented Mar 18, 2015 at 19:32
  • It's actually a matrix of objects, which as you say is just a list with a dimension attribute. You can put anything you want in it, including functions. It works basically like a list, except that you can access it with 2-dimensional indices. Commented Mar 18, 2015 at 19:44
  • You can also access items in a non-dimensioned lists with 2 or greater length vectors. Commented Mar 18, 2015 at 23:21
  • @BondedDust I know about that, but this isn't a nested list Commented Mar 19, 2015 at 1:23

1 Answer 1

1

Making one is fairly trivial:

mtx <- matrix( list(letters[1:2]), 4,4) mtx #---------- [,1] [,2] [,3] [,4] [1,] Character,2 Character,2 Character,2 Character,2 [2,] Character,2 Character,2 Character,2 Character,2 [3,] Character,2 Character,2 Character,2 Character,2 [4,] Character,2 Character,2 Character,2 Character,2 

The attribute (and the function that retrieves it) is named "dim". I would not expect it to be very much different in terms of access efficiency. Matrices in R are really just folded vectors.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.