[R] nicer matrix construction: rbind()

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Nov 30 10:55:48 CET 2005


On Wed, 30 Nov 2005, Martin Maechler wrote:

> Just a small remark on "R coding style" :
>
>>>>>> "Sean" == Sean Davis <sdavis2 at mail.nih.gov>
>>>>>>     on Tue, 29 Nov 2005 08:34:39 -0500 writes:
>
>      Sean> <............>
>
>      Sean> x <- matrix(c(1,1,1,2,2,2,1,1,1,1,1,2),nr=2,byrow=TRUE)
>
>      Sean>  <.....>
>            (a very helpful answer to Georg's question; thanks, Sean!)
>
> I've seen example code like this in many places,
> and I'd like advocate a more readable alternative
>
>   x <- rbind(c(1,1,1, 2,2,2)
>              c(1,1,1, 1,1,2))
>
> {efficiency really not being of any concern;
> we are talking about didactical examples}.

But introducing unnecessary concepts is a concern, and I think

x <- matrix(c(1, 1, 1, 2, 2, 2,
               1, 1, 1, 1, 1, 2),
             nrow = 2, byrow = TRUE)

is clearer (and does not leave me wondering about the non-obvious choice 
of spaces).

Abbreviating argument names in didactical examples (or in R code) is a bad 
practice and sometimes clobbers you.  For example whoever used 'lab' in 
the examples of axis() invited confusion between the argument 
'labels' and the graphical par 'lab', confusion which duly got propagated 
to plot.default having a 'lab' argument and passing it nowhere.

> I believe  rbind() -- and indenting ("white space"
> in general!) should be used much more for matrix construction --
> because of quick "visual validation"
> at least for small examples.
>
> {and if you'd use ESS (http://ESS.r-project.org/),
> a simple <Tab> key press automatically indents the 2nd line correctly!}
>
> Martin Maechler, ETH Zurich

-- 
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