[R] Extracting Hash via Vector

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Tue Jan 13 12:27:33 CET 2009


Gundala Viswanath wrote:
> Dear all,
>
> Suppose I have a hash created with this
>
>  x <- list()
> for (i in c('test', 'some', 'more')){
>    x[[i]] <- runif(1)
> }
>   

this is not really a hash, even though you can retrieve elements by
name, and not only by integer index.
also, try to navigate out of the r inferno, see sec 2 in 'the r inferno'
(at http://www.burns-stat.com).



> then I want to extract the elem of that hash with
> a vector
>
>   
>> q <- c("some", "more", "not_there")
>>     
>
> But why this failed?
>   

?'[['
/Recursive

>   
>> extracted <- x[[q]]
>>     
> Error in x[[q]] : subscript out of bounds
>
> we expect the output of 'extracted' to be
> a vector as well. When the key is not present
> to give "NA" in vector
>   

x[[q]] is equivalent to x[['some']][['more']][['not_there']].  since
x[['some']] is an atomic integer vector, it won't collaborate with
[['more']], and you're done -- since this fails, the recursive indexing
fails.

on the side, this fails as well (guess why), though some might expect it
should work fine:

x[[c('some', 1)]]
# expected an integer, but subscript out of bounds reported

arguably, 'index out of bounds' is not the most enlightening message in
cases such as this one:

x = 1:10
x[11]
# NA, as you might want
x[[11]]
# d'oh, index out of bounds

vQ




More information about the R-help mailing list