[R] structure vs. matrix
Prof Brian Ripley
ripley at stats.ox.ac.uk
Sun Nov 4 16:15:11 CET 2007
On Sun, 4 Nov 2007, Duncan Murdoch wrote:
> On 04/11/2007 1:28 AM, Edna Bell wrote:
>> Hi R Gurus!
>>
>> When creating a matrix, is it better to use the structure function or
>> the matrix function, please?
>
> I'd use the matrix() function. You can do it with structure(), and your
> code might be a little faster, but it will be harder to read, will break
> if someone ever changes the low-level implementation of matrices, e.g.
> by replacing it with the Matrix class.
For the record
A <- <some data>
dim(A) <- c(nr, rc)
is faster than either matrix() or structure(), and seems at least as easy
to read. matrix() has the advantage that it will replicate the data
to the necessary length, but both will make copies that my version does
not if you have the right length of data.
But this is only worth worrying about if you have large matrices.
--
Brian D. Ripley, ripley at stats.ox.ac.uk
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272866 (PA)
Oxford OX1 3TG, UK Fax: +44 1865 272595
More information about the R-help
mailing list