[R] getting the "name" of an object

hadley wickham h.wickham at gmail.com
Wed Oct 22 16:43:42 CEST 2008


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 ?

Hadley


-- 
http://had.co.nz/



More information about the R-help mailing list