Skip to content

accessing the attributes of a list inside lapply()

3 messages · Adrian Alexa, Eric Lecoutre, Spencer Graves

#
Hello R-users, 


I have the following problem, that I want to solve efficiently:


I have a named list, for example:
$a
[1] 1

$b
[1] 3

$c
[1] "asd"


I know that I can iterate through it using lapply() function, but I
would also like to able to get the list names or some attributes of l
in the lapply(). For example if I use names() function in the call of
lapply() I get:
$a
NULL

$b
NULL

$c
NULL
 

My question is if I can get something like:
$a
[1] a

$b
[1] b

$c
[1] c
 

I can do this very easy with a for() loop but my list is quite big and
I would like to get a decent running time. I don't need only the
attributes of the list(I can obtain them by using attributes() or
attr() function), but for my list the names of the elements are given
me information that I need. Also I must mention that the elements of
the list can by of any type.


Any solution is welcome.

 

Many thanks, 

Adrian
#
Hi,

What about:

 >  as.list(names(l))
[[1]]
[1] "a"

[[2]]
[1] "b"

[[3]]
[1] "c"


HTH,

Eric
At 15:59 19/11/2004, Adrian Alexa wrote:
#
Maybe I misunderstand your problem, but I wonder if you've 
considered "names": 

 > l <- list(a = 1, b = 3, c = 'asd')
 > names(l)
[1] "a" "b" "c"    

      hope this helps.  spencer graves
p.s.  I can't parse your "lapply(l, get_attr)".  In R 1.9.1 and R 2.0.0 
Patched, I get the following: 

 > lapply(l, get_attr)
Error in match.fun(FUN) : Object "get_attr" not found
Adrian Alexa wrote: