Skip to content

changing a list element's name during execution in lapply - possible?

6 messages · David Winsemius, Mark Heckmann, jim holtman +1 more

#
Happy New Year, all!

I want to do calculations on each element of a list l, but i want the  
returned list element to be named differently after the calculation.
Is it possible to do the renaming somehow within the lapply call?

	l <- list(a=NA, b=NA)
	lapply(l, function(x) {names(x) <- "new name";  return(x) })

This does not work, any ideas?
TIA

???????????????????????????????????????
Mark Heckmann
Dipl. Wirt.-Ing. cand. Psych.
Vorstra?e 93 B01
28359 Bremen
Blog: www.markheckmann.de
R-Blog: http://ryouready.wordpress.com
#
On Jan 1, 2010, at 8:21 AM, Mark Heckmann wrote:

            
It did "work" in the sense that it created a list of the same  
structure with each node now named "new name". If you want that named  
list to become "l", then you need to do an assignment:

l <- lapply(l, function(x) {names(x) <- "new name";  return(x) })
 > l
$a
new name
       NA

$b
new name
       NA
#
Try this:

# same args as lapply.  FUN must return named components.
lapplyWithRename <- function(...) {
	x <- lapply(...)
	names(x) <- sapply(x, names)
	lapply(x, function(x) { names(x) <- NULL; x })
}

# test function - if x is "A" then f returns c("Name A" = "A")
f <- function(x) structure(x, .Names = paste("Name", x))

L <- list(a="A", b="B")
lapplyWithRename(L, f)

Output looks like this:
$`Name A`
[1] "A"

$`Name B`
[1] "B"
On Fri, Jan 1, 2010 at 8:21 AM, Mark Heckmann <mark.heckmann at gmx.de> wrote: