Skip to content

How get list element name in R 3.2.0

2 messages · Marc Girondot, Henrik Bengtsson

#
Dear list-members,
I find a annoying difference between R 3.1.3 and R 3.2.

To get the element name of a list within lapply() or mclapply() call, I 
used the trick below:
For example:

essai <- list(T2345=c(5, 6, 7), T5664=c(9, 12, 17, 16))
lapply(essai, function(x) plot(x, main= names(essai)[substitute(x)[[3]]]))

It works fins in R 3.1.3 however in R 3.2 it produces an error:
 > essai <- list(T2345=c(5, 6, 7), T5664=c(9, 12, 17, 16))
 > lapply(essai, function(x) plot(x, main= 
names(essai)[substitute(x)[[3]]]))

  Error in names(essai)[substitute(x)[[3]]] :
   type 'symbol' d'indice incorrect

I don't see if this difference is noted is the list of changes:
http://cran.r-project.org/doc/manuals/r-devel/NEWS.html

If it is not a bug but a feature, what is the new way to get the list 
element name within a lapply or mclappy function.

Thanks a lot

Marc Girondot
#
I'd say what you did in the past was definitely a hack that made too
strong assumptions on the internal implementation of lapply() etc.  It
basically relied on *apply() to loop over the elements using an index
variable.  There any many ways to do this and it seems like in R 3.2.0
there was change.  Actually, it does also not work as you expect in R
3.1.3 (but you don't get the error).  This is what you basically did:

## R 3.0.3:
$T2345
[1] 1

$T5664
[1] 2


## R 3.1.3:
$T2345
[1] 2

$T5664
[1] 2

NOTE how you don't get indices you expect, and therefor not the names either.

## R 3.2.0:
$T2345
i

$T5664
i

The latter will obviously not work as indices.

My rule of thumb: Anytime you find yourself using substitute() and
get()/assign(), there's probably a better way to do it.  Example:
or
If names are unique, this also works:
/Henrik
On Sun, Apr 26, 2015 at 1:28 PM, Marc Girondot <marc_grt at yahoo.fr> wrote: