[R] getting the "name" of an object
Peter Dalgaard
P.Dalgaard at biostat.ku.dk
Wed Oct 22 17:57:23 CEST 2008
hadley wickham wrote:
> On Wed, Oct 22, 2008 at 9:34 AM, Duncan Murdoch <murdoch at stats.uwo.ca> wrote:
>
>> 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.
>>
>
> This would be equally hard to do in Java - it is very very unusual to
> create variables on the fly, and you would have to do some
> sophisticated reflection stuff. If you're used to using java, maybe
> you should think about how you would accomplish this task there -
> surely you'd would iterate along an ArrayList, saving the results back
> into another ArrayList ?
>
I don't really see the point of doing this at all, but if need be, how about
l <- lapply(mylist,mean)
mapply(assign, paste("foo",names(l),sep="."), l,
MoreArgs=list(env=.GlobalEnv))
--
O__ ---- Peter Dalgaard Øster Farimagsgade 5, Entr.B
c/ /'_ --- Dept. of Biostatistics PO Box 2099, 1014 Cph. K
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
More information about the R-help
mailing list