[R] The end of Matlab

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Dec 12 09:55:14 CET 2008

On Fri, 12 Dec 2008, Duncan Murdoch wrote:

> On 11/12/2008 9:45 PM, Mike Rowe wrote:
>> Greetings!
>> I come to R by way of Matlab.  One feature in Matlab I miss is its
>> "end" keyword.  When you put "end" inside an indexing expression, it
>> is interpreted as the length of the variable along the dimension being
>> indexed.  For example, if the same feature were implemented in R:
>> my.vector[5:end]
>> would be equivalent to:
>> my.vector[5:length(my.vector)]
> And if my.vector is of length less than 5?

Also consider


>> or:
>> this.matrix[3:end,end]
>> would be equivalent to:
>> this.matrix[3:nrow(this.matrix),ncol(this.matrix)]   # or
>> this.matrix[3:dim(this.matrix)[1],dim(this.matrix)[2]]
>> As you can see, the R version requires more typing, and I am a lousy
>> typist.
> It doesn't save typing, but a more readable version would be
> rows <- nrow(this.matrix)
> cols <- ncol(this.matrix)
> this.matrix[3:rows, cols]

I would have used

this.matrix[-(1:2), ncol(this.matrix)]

which I find much clearer as to its intentions.

>> With this in mind, I wanted to try to implement something like this in
>> R.  It seems like that in order to be able to do this, I would have to
>> be able to access the parse tree of the expression currently being
>> evaluated by the interpreter from within my End function-- is this
>> possible?  Since the "[" and "[[" operators are primitive I can't see
>> their arguments via the call stack functions...
>> Anyone got a workaround?  Would anybody else like to see this feature
>> added to R?

Learning to use the power of R's indexing and functios like head() and 
tail() (which are just syntactic sugar) will probably lead you not to miss 

> I like the general rule that subexpressions have values that can be evaluated 
> independent of context, so I don't think this is a good idea.

Also, '[' is generic, so it would need to be done in such a way that it 
applied to all methods.  As arguments other than the first are passed 
unevaluated to the methods, I don't think this is really possible (you 
don't even know if the third argument to `[` is a dimension for a method).

Also, this would effectively make 'end' a reserved word, or 3:end is 
ambiguous (or at best context-dependent).

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