[R] how does a valid subscript can produce an "subscript out of bounds" error?

peter dalgaard pdalgd at gmail.com
Sat Jul 5 16:49:39 CEST 2014


On 05 Jul 2014, at 16:19 , Witold E Wolski <wewolski at gmail.com> wrote:

> Thank you. You example helped to FIX IT.
> 
> The problem is I guess somehow related to:
>> class(msexp$pepinfo$transition_group_id)
> [1] "factor"
> 
> and the whole R type conversion , riddle.
> 
> For subscripts my intuition is:  either require integer or do the
> "cast" to the rowname type (character).
> However, it seems that R somehow prefers to cast factors to integers...
> 
> it seems that %in% "casts" both vectors to the same type. But to which one?
> 
> Oh, I guess all this is neatly explained in the R standard ... but
> websearching for it just returns:
> standard deviation
> 

From help("[")

     The index object ‘i’ can be numeric, logical, character or empty.
     Indexing by factors is allowed and is equivalent to indexing by
     the numeric codes (see ‘factor’) and not by the character values
     which are printed (for which use ‘[as.character(i)]’).

One reason for hanging on to this convention is that it allows you to do

plot(x, y, col=c("red","blue")[sex])

Another reason is that it is the broader definition: It works for indexing vectors that do not have names.

> 
> a frustrated R user.
> 
> On 5 July 2014 02:18, Duncan Murdoch <murdoch.duncan at gmail.com> wrote:
>> On 04/07/2014, 6:35 PM, Witold E Wolski wrote:
>>> how does a valid subscript (see first 2 lines) can produce an
>>> "subscript out of bounds" error (see line 4)?
>>> 
>>> 
>>> 1> sum(!rownames(msexp$rt) %in% msexp$pepinfo$transition_group_id)
>>> [1] 0
>>> 2> sum(!msexp$pepinfo$transition_group_id %in% rownames(msexp$rt))
>>> [1] 0
>>> 3> class(msexp$rt)
>>> [1] "matrix"
>>> 4> msexp$rt = as.matrix(msexp$rt[msexp$pepinfo$transition_group_id,])
>>> Error in msexp$rt[msexp$pepinfo$transition_group_id, ] :
>>>  subscript out of bounds
>>>> 
>>> 
>> 
>>> x <- matrix(1,1,1)
>>> rownames(x) <- colnames(x) <- "23"
>>> 23 %in% rownames(x)
>> [1] TRUE
>>> x[23,]
>> Error in x[23, ] : subscript out of bounds
>> 
> 
> 
> 
> -- 
> Witold Eryk Wolski
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list