Skip to content

how to 'get' an object that is part of a list

8 messages · jim holtman, Duncan Murdoch, Gabor Grothendieck +1 more

#
This might be an trivial thing but I am stuck.

Consider: 
 
xx <- list(a=1:5, b=letters[1:5])
 
Although object xx is accessible through its name,
how can object xx$b be accessed similarly through its name?
$a
[1] 1 2 3 4 5

$b
[1] "a" "b" "c" "d" "e"
Error in get(x, envir, mode, inherits) : variable "xx$b" was not found
 
get("xx")$b will not work in my case because it will probably require
parsing to make it work within a function. E.g.

my.length <- function(...) {
	names <- as.character(substitute(list(...)))[-1]
	sapply(names, FUN=function(x){y <- get(x); length(y)})
}
xx 
 2
Error in get(x, envir, mode, inherits) : variable "xx$a" was not found
Error in get(x, envir, mode, inherits) : variable "xx$a" was not found
	
Thank you.
 
Christos Hatzis, Ph.D.
Nuvera Biosciences, Inc.
400 West Cummings Park
Suite 5350
Woburn, MA 01801
Tel: 781-938-3830
www.nuverabio.com
#
On 12/24/2006 12:06 AM, Christos Hatzis wrote:
name <- "b"
xx[[name]]

will work.

Duncan Murdoch
#
Is this what you are looking for:
+    f <- function(nm, val) length(val)
+    mapply(f, make.names(as.list(match.call()[-1])), list(...))
+ }
xx xx.b
   2    5
On 12/24/06, jim holtman <jholtman at gmail.com> wrote:
#
Thank you Gabor.  Very interesting solution.
If I get it right, the first argument in function f is just a placeholder to
help extract the right element out of the list(...) that is passed to
length.  Very smart trick.

Jim's solution appears a bit simpler, at least along the lines that I was
thinking:

my.length <- function(...) {
	names <- as.character(substitute(list(...)))[-1]
	sapply(names, function(x){y <- eval(parse(text=x)); length(y)})
} 

-Christos

-----Original Message-----
From: Gabor Grothendieck [mailto:ggrothendieck at gmail.com] 
Sent: Sunday, December 24, 2006 7:41 AM
To: jim holtman
Cc: christos at nuverabio.com; 
Subject: Re: [R] how to 'get' an object that is part of a list

Is this what you are looking for:
+    f <- function(nm, val) length(val)
+    mapply(f, make.names(as.list(match.call()[-1])), list(...)) }
xx xx.b
   2    5
On 12/24/06, jim holtman <jholtman at gmail.com> wrote:
#
my.length.2 also has the advantage of eliminating the eval.
On 12/25/06, Christos Hatzis <christos at nuverabio.com> wrote:
#
True.  Thanks again. 

-----Original Message-----
From: Gabor Grothendieck [mailto:ggrothendieck at gmail.com] 
Sent: Monday, December 25, 2006 8:34 AM
To: christos at nuverabio.com
Cc: r-help at hypatia.math.ethz.ch
Subject: Re: [R] how to 'get' an object that is part of a list

my.length.2 also has the advantage of eliminating the eval.
On 12/25/06, Christos Hatzis <christos at nuverabio.com> wrote: