Re: [Rd] returning information from functions via attributes rather than return list

From: Paul Johnson <pauljohn32_at_gmail.com>
Date: Wed, 04 Jan 2012 14:19:44 -0600

On Tue, Jan 3, 2012 at 3:59 PM, Simon Urbanek <simon.urbanek_at_r-project.org> wrote:
> Paul,
>
> On Jan 3, 2012, at 3:08 PM, Paul Johnson wrote:
>
>> I would like to ask for advice from R experts about the benefits or
>> dangers of using attr to return information with an object that is
>> returned from a function. I have a feeling as though I have cheated by
>> using attributes, and wonder if I've done something fishy.
>>
>> Maybe I mean to ask, where is the dividing line between attributes and
>> instance variables?  The separation is not clear in my mind anymore.
>>
>> Background: I paste below a function that takes in a regression object
>> and make changes to the data and/or call and then run a
>> revised regression.  In my earlier effort, I was building a return
>> list, including the new fitted regression object plus some
>> variables that have information about the changes that a were made.
>>
>> That creates some inconvenience, however.  When the regression is in a
>> list object, then methods for lm objects don't apply to that result
>> object. The return is not an lm anymore.
>
> Why don't you just subclass it? That's the "normal" way of doing things - you simply add additional entries for your subclass (e.g. m$myItem1, m$myItem2, ...), prepend your new subclass name and you're done. You can still dispatch on your subclass before the superclass while superclass methods just work as well..
>
> Cheers,
> Simon
>

Yes. I see that now.

But I'm still wondering about the attribute versus variable question. To the programmer, is there any difference between returning information as attributes or variables?

Does R care if I do this:

class(res) <- c("mcreg", "lm")
attr(res, "centeredVars") <- nc

Or this:

class(res) <- c("mcreg", "lm")
res$centeredVars <- nc

Is there some place "down there," in the C foundations of R, where an attribute is just a variable, as is centeredVars?

pj

-- 
Paul E. Johnson
Professor, Political Science
1541 Lilac Lane, Room 504
University of Kansas

______________________________________________
R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel
Received on Wed 04 Jan 2012 - 20:24:51 GMT

This quarter's messages: by month, or sorted: [ by date ] [ by thread ] [ by subject ] [ by author ]

All messages

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 04 Jan 2012 - 23:40:06 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-devel. Please read the posting guide before posting to the list.

list of date sections of archive