[R] lapply over list and the respective name of the list item

From: Thaler, Thorn, LAUSANNE, Applied Mathematics <Thorn.Thaler_at_rdls.nestle.com>
Date: Tue, 12 Apr 2011 13:34:48 +0200

Hi all,

I find myself sometimes in the situation where I lapply over a list and in the particular function I'd like to use the name and or position of the respective list item. What I usually do is to use mapply on the list and the names of the list / a position list:

o <- list(A=1:3, B=1:2, C=1)
mapply(function (item, name) paste(name, sum(item), sep="="), o, names(o))
mapply(function (item, pos) paste(pos, sum(item), sep="="), o, seq_along(o))

[another way would be, of course, to use a for loop, but I'm slightly reluctant to use for loops knowing that I definitely misuse lapply sometimes]

Now I was wondering whether there is a better way of doing this? Or is the mapply approach already the best way? In other words, is there any possibility within lapply to get any information about the context of the respective item?

To give you an example where this could be useful:

Imagine we have a dataframe and we want to replicate (more general apply a function to) each column and the result should be a dataframe again, where the new columns bear the name of their respective parent column amended by some suffix. Using mapply I'd do something like:

d <- data.frame(A=1:3, B=2:4)
Reduce(cbind, mapply(function (col, nam) {

	td <- as.data.frame(do.call(cbind, rep(list(col), 3)))
	names(td) <- paste(nam, 1:3, sep = "_")
      td}, d, names(d), SIMPLIFY=FALSE))

Any suggestions? Or is it already the state of the art? Any help appreciated.

BR Thorn

R-help_at_r-project.org mailing list
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. Received on Tue 12 Apr 2011 - 11:41:38 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 12 Apr 2011 - 12:20:30 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive