Skip to content

Extracting Hash via Vector

7 messages · Gundala Viswanath, Henrique Dallazuanna, Wacek Kusnierczyk +1 more

#
Dear all,

Suppose I have a hash created with this

 x <- list()
for (i in c('test', 'some', 'more')){
   x[[i]] <- runif(1)
}

then I want to extract the elem of that hash with
a vector
But why this failed?
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

- Gundala Viswanath
Jakarta - Indonesia
#
Gundala Viswanath wrote:
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).
?'[['
/Recursive
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
#
Wacek Kusnierczyk wrote:
expected a double, not an integer, of course, since the value comes from
runif.

vQ
#
Wacek Kusnierczyk wrote:
?sj, one more lousy statement.  x[['some']] is an atomic *double* vector
*with no element named 'more'*, hence x[['some']][['more']] won't work. 
anyway, the point is that 'some' is used as an index on the first
element of x, rather than on x itself -- because of the recursive indexing.

one might argue that recursive indexing should be done explicitly, by
repeating the use of [[, and that [[q]] performing recursive indexing
when length(q) > 1 is yet another 'optimization' in r that easily leads
to confusion.  it is not unreasonable to think that x[[q]] might return
a concatenation of the respective elements of x:

x = as.list(1:2)
x[1]
# [[1]] 1
x[1:2]
# [[1]] 1
# [[2]] 2
x[[1]]
# 1
x[[1:2]]
# 1 2 (but it will rather fail)


vQ
#
Thanks for your most reasonable reply, Henrique.

- Gundala Viswanath
Jakarta - Indonesia
On Tue, Jan 13, 2009 at 8:01 PM, Henrique Dallazuanna <wwwhsd at gmail.com> wrote: