[R] The end of Matlab

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Fri Dec 12 16:00:01 CET 2008

>> Wacek:
>>> x[3:]
>>> instead of
>>> x[3:length(x)]
>>> x[3:end]
>> I don't think that would help: 
>> what to use for end - 3 within the convention that negative values mean 
>> exclusion?
> might seem tricky, but not impossible:
> x[-2]
> # could mean 'all except for 2nd', as it is now
> x[1:-2]
> # could mean 'from start to the 2nd backwards from the end'
> since r disallows mixing positive and negative indexing, the above would
> not be ambiguous.  worse with
> x[-3:-1]
> which could mean both 'except for 3rd, 2nd, and 1st' and 'from the 3rd
> to the 1st from the end', and so would be ambiguous.  in this context,
> indeed, having explicit 'end' could help avoid the ambiguity.

on the other hand, another possible solution would be to have ':' mean,
inside range selection expressions, not the usual sequence generation,
but rather specification of start and end indices:

# from 1st to 2nd, inclusive

# same as above

# same as above

# from 1st to 2nd from the end, not x[c(1,0,-1,-2)]

# no way, mixed indices

# from 2nd to 1st, both from the end, not x[c(-2,-1)]

x[length(x) + -1:0]
# same as above

# except for 2nd and 1st

# same as above

# from 2nd up

x[seq(2, max(2, length(x)))]
# same as above (would not be without max)

# up to 3rd

# same as above

# up to 3rd from the end

x[seq(1, length(x)-2)]
# same as above

with additional specifications for the behaviour in case of invalid
indices and decreasing indices:

# from the 2nd to the 1st, in reverse order
# or nothing, invalid indexing

which can be easily done with the unambiguous x[seq(2,1)] or x[c(2,1)]

this is daydreaming, of course, because such modifications would break
much old code, and the benefit may not outweigh the effort.


More information about the R-help mailing list