[Rd] Negative integer subscripts in [[?

Duncan Murdoch murdoch at stats.uwo.ca
Tue Nov 10 01:55:06 CET 2009


On 09/11/2009 4:38 PM, William Dunlap wrote:
> Should negative subscripts be outlawed in
>    x[[subscript]]
> ?  
> 
> Currently, if subscript is a scalar then it can only
> be negative if length(x)==1 (otherwise [[ throws an
> error).  If length(subscript)>1 then it gets treated
> as an attempt to recursively extract an element of
> a nested list.
> 
>> list(10,20)[[-1]] # get the last element out of 2
> [1] 20
>> list(10,20,30)[[-(1:2)]] # get the last of 3?  No.
> Error in list(10, 20, 30)[[-(1:2)]] :
>   attempt to select more than one element
>> list(10,list(20,30))[[-c(1:2)]] # see how recursive subscripting is
> done
> [1] 20
> 
> If negative subscripts were not allowed in [[ then 
> there might be a little less confusion about [[.

I agree, it would be better not to allow negatives here, but as John 
said it's probably too late to do away with them.

> (If recursive subscripting were done by a list instead
> of by an integer or character vector there might be
> less confusion and it would be more flexible.)

I don't follow this.  Recursive lists are trees, and you specify a 
single element of a tree by specifying a sequence of indices.  Why would 
it be less confusing to give a list?  What extra flexibility could there 
be?  I suppose you could mix integer and character indices, but what 
would be meant by x[[ list(1, list(2,3), 4) ]] ?

I don't know the original motivation for allowing vector indexing to 
lists, but I extended it to pairlists so that it would be possible to 
specify a location within a function exactly, by walking down the parse 
tree.  I think it's something that would be rarely used, but when you 
need it, it's very handy.

Duncan Murdoch



More information about the R-devel mailing list