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

Thaler, Thorn, LAUSANNE, Applied Mathematics Thorn.Thaler at rdls.nestle.com
Tue Apr 12 13:34:48 CEST 2011

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,
mapply(function (item, pos) paste(pos, sum(item), sep="="), 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

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

BR Thorn

More information about the R-help mailing list