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:> essai <- list(T2345=c(5, 6, 7), T5664=c(9, 12, 17, 16))
> idxs <- lapply(essai, function(x) substitute(x)[[3]])
> idxs
$T2345
[1] 1
$T5664
[1] 2
## R 3.1.3:> essai <- list(T2345=c(5, 6, 7), T5664=c(9, 12, 17, 16))
> idxs <- lapply(essai, function(x) substitute(x)[[3]])
> idxs
$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:> essai <- list(T2345=c(5, 6, 7), T5664=c(9, 12, 17, 16))
> idxs <- lapply(essai, function(x) substitute(x)[[3]])
> idxs
$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:
> essai <- list(T2345=c(5, 6, 7), T5664=c(9, 12, 17, 16))
> lapply(seq_along(essai), function(idx) plot(essai[[idx]],
main=names(essai)[idx]))
or
> essai <- list(T2345=c(5, 6, 7), T5664=c(9, 12, 17, 16))
> mapply(essai, names(essai), FUN=function(x, name) plot(x, main=name))
If names are unique, this also works:
> essai <- list(T2345=c(5, 6, 7), T5664=c(9, 12, 17, 16))
> lapply(names(essai), function(name) plot(essai[[name]], main=name))
/Henrik
On Sun, Apr 26, 2015 at 1:28 PM, Marc Girondot <marc_grt at yahoo.fr>
wrote:> 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
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.