0

I am currently working in R and I am trying to populate a matrix with a some for loops. However, I keep getting the "number of items to replace is not a multiple of replacement length" error. The way I set my matrix() is that I specified nrow (because I am sure of the size) and I leave the ncol blank.

How can I create a matrix that dynamically allocate the dimensions?

Any recommendations? Thank you.

Brandon Bertelsen
  • 43,807
  • 34
  • 160
  • 255
Concerned_Citizen
  • 6,548
  • 18
  • 57
  • 75
  • 2
    It will be hard for anyone to help unless you provide a reproducible example that others can run on their own machines. This would include a small subset of your data (using dput()), for instance. See [here](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for more info. – joran Aug 02 '11 at 18:28
  • 1
    Let me rephrase my question. How can I create a matrix that dynamically allocate the dimensions. Thank you. – Concerned_Citizen Aug 02 '11 at 18:44
  • 1
    @GTyler - Saying 'How can I create a matrix that dynamically allocate the dimensions?' is still fairly vague and open to numerous interpretations, and will elicit fairly vague, general answers. Give us an example of what you're trying to do. – joran Aug 02 '11 at 19:19

1 Answers1

2

A couple of options spring to mind:

  • Make an informed guess as to the size of the matrix and allocate accordingly. Then have your code check to see if you would exceed the limits chosen and expand the object. If you expand by a reasonable chunk size (i.e. don't add just 1 column, add 10 or 20 or n depending on the size of your problem, whatever is reasonable) then you won't incur the copy/expand overhead that often, which is what bogs loops down if written badly.

  • Store the data/result in a list, each component of which would be one row of your matrix. That way you fill in the object as you go along, and then can either process the resulting list into a matrix with padding, or just work directly with the list. If each row can be of a different length (number of columns) then it doesn't make sense to store as a matrix in the first place and the list is the better option.

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
  • is this a chicken before the egg kind of question? Why do we have to initialize matrices in this fashion? – Brandon Bertelsen Aug 02 '11 at 20:25
  • 1
    If you don't know the exact dimension, it is a pain to grow to sufficient size at each iteration because you suffer the overhead of the copy/enlarge process at each iteration. If you can circumvent that by incurring just a couple/few copy/enlarges, on your own terms, during iteration, the end result will be faster code. – Gavin Simpson Aug 02 '11 at 20:46
  • 1
    @Brandon, see The R inferno for more info on preallocation over growing your objects. www.burns-stat.com/pages/Tutor/R_inferno.pdf – Roman Luštrik Aug 03 '11 at 08:35