On 10/22/2008 10:02 AM, francois Guilhaumon wrote:
Hello,

I'm looking for a way to get the "name" of an object when it is used
within an "sapply".

More precisely, with a simple example :

I have a named list of objects :

myList = list(a=rnorm(10),b=rnorm(10),c=rnorm(10))

I would like to create a new object from each of the components of
myList using the "sapply" function, for example to get the mean of all
components of myList :

createVarMean = function(obj){

      obj.name = ******
      obj.mean = mean(obj)
      assign(obj.name,obj.mean)

}#end of createVarMean

sapply doesn't pass the names in, but there are other choices:

sapply(seq_along(myList), function(i) list(obj.name=names(myList)[i], obj.mean = mean(myList[[i]])))

which iterates over the indices of myList, rather than over the elements of it. But a simple sapply(myList, function(obj) mean(obj)) is probably preferable, since it attaches the names in a nice way:

> sapply(myList, function(obj) mean(obj))
         a          b          c
-0.4097454 -0.5057526 -0.2204035

Using :

sapply(myList,createVarMean)

Should then create all the objects.

Any idea to get the names ? Perhaps using object oriented programming
(is there an equivalent of the "this" syntax of Java in R ?) ?

Object oriented stuff in R is quite different from Java, because R doesn't have pointers or references except in very special cases.

Duncan Murdoch


I don't want to use a loop here.

thank you for your time and trouble,

François.

______________________________________________
R-help@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.

______________________________________________
R-help@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.

Reply via email to