Bazz Bazz - 1 year ago 69
R Question

Accessing unnamed list elements inside base::with()

My question is whether this is possible. Given a list

lst <- list(a = 1, 2)

One can put
with(lst, a)
to return the first element. But can you return the second using
element without first naming it?

Doesn't work:

with(lst, [[2]])
with(lst, `2`)

I suspect that this is not possible because
with(lst, ls(all.names = TRUE))
gives just
. But does anyone know different?

I realise why
with(lst, 2)
could never work. And of course
is a function, so it is clear that my first attempt would confuse R. However, it would be feasible that with would give special names to unnamed arguments so that they were accessible without having to re-access the list separately. For example, the second element could be called
in the environment set up by with. This is not the case, though.

In this example one would simply use
. But I am thinking in terms of a complex expression for a large multi-levelled list, for which some elements are named and others not. The code would be much more readable using a
statement to start at a convenient level of subsetting. But having some needed elements unnamed is a barrier for this.

Answer Source

No, this is not possible. You can't reference an unnamed object from within a list.

lst <- list(a = 1, 2)

This is what with does:

eval(substitute(a), lst, enclos = parent.frame())
#[1] 1

The only object accessible from within lst is a:

eval(substitute(ls()), lst, enclos = parent.frame())
#[1] "a"

I'd suggest naming all components of the list. (And to be honest, I don't really see a common use case.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download