[R] name returned by lapply

Gavin Simpson gavin.simpson at ucl.ac.uk
Fri Jul 18 14:09:01 CEST 2008


On Fri, 2008-07-18 at 13:45 +0200, Antje wrote:
> Hi there,
> 
> I have a very simple question. If I execute the following code:
> 
> 
> test <- function(x) {
> 	name <- paste(x,"info_within_function")
> 	c(1,2,3,4,5)
> }
> 

Here your test is returning c(1,2,3,4,5), and is doing nothing with
name, other than to create the object, 'name'.

## ones presumes your real example is more complicated than this so
## I'll stick with the function test, but just have it return the
## values you asked for
test <- function(x) {
	c(1,2,3,4,5)
}

##  we then apply this
ret <- lapply(1:10, test)

## now that we have a list, we change the names to what you want
names(ret) <- paste(1:10, "info_within_function")

This does cause a problem though as you can't access the components
directly via:

ret$1 info_within_function

You need to quote them:

ret$`1 info_within_function`

And even if you replace the space with a "_", the same problem persists:

names(ret) <- paste(1:10, "info_within_function", sep = "_")
ret$1_info_within_function
ret$`1_info_within_function`

So depending on why you want the list components named this way, you
might consider altering the name so that it doesn't start with a number
and doesn't contain spaces, otherwise you'll need to quote the names
when trying to access the components of the list by name.

Does that help?

G

> ret <- lapply(1:10, test)
> 
> 
> , I end up with a list and each entry is just numbered [[1]], [[2]], ... [[10]]
> 
> How can I force the result entries gettings names which are determined within 
> the function. For this example, I'd like the entries named like:
> 
> "1 info_within_function" instead of [[1]]
> "2 info_within_function" instead of [[2]]
> and so on.
> (that's why I put this strange "name <- ..." line inside)
> 
> Can anybody help me what I have to do to get the returned list entries like this?
> 
> Thanks a lot!
> 
> Antje
> 
> ______________________________________________
> 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.
-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 Dr. Gavin Simpson             [t] +44 (0)20 7679 0522
 ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%



More information about the R-help mailing list