Re: [R] Object attributes in R

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Wed 11 Oct 2006 - 19:38:25 GMT

You can define your own class then define [ to act any way you would like:

"[.myobj" <- function(x, ...) {

	y <- unclass(x)[...]
	attributes(y) <- attributes(x)
	y

}

tm <- structure(1:10, units = "sec", class = "myobj") tm
tm[3:4] # still has attributes         

On 10/11/06, Michael Toews <mwtoews@ucalgary.ca> wrote:
> Hi,
> I have questions about object attributes, and how they are handled when
> subsetted. My examples will use:
> tm <- (1:10)/10
> ds <- (1:10)^2
> attr(tm,"units") <- "sec"
> attr(ds,"units") <- "cm"
> dat <- data.frame(tm=tm,ds=ds)
> attr(dat,"id") <- "test1"
>
> When a "primitive class" object (numeric, character, etc.) is subsetted,
> the attributes are often stripped away, but the rules change for more
> complex classes, such as a data.frame, where they 'stick' for the
> data.frame, but attributes from the members are lost:
> tm[3:5] # lost
> ds[-3] # lost
> str(dat[1:3,]) # only kept for data.frame
>
> Is there any way of keeping the attributes when subsetted from primitive
> classes, like a fictional "attr.drop" option within the "[" braces? The
> best alternative I have found is to make a new object, and copy the
> attributes:
> tm2 <- tm[3:5]
> attributes(tm2) <- attributes(tm)
>
> However, for the data.frame, how can I copy the attributes over (without
> using a for loop -- I've tried a few things using sapply but no success)?
> Also I don't see how this is consistent with an empty index, "[]", where
> attributes are always retained (as documented):
> tm[]
>
> I have other concerns about the evaluation of objects with attributes
> (e.g. ds/tm), where the attributes from the first object are retained
> for the output, but this evaluation of logic is a whole other can of
> worms I'd rather keep closed for now.
>
> +mt
>
> ______________________________________________
> R-help@stat.math.ethz.ch 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@stat.math.ethz.ch 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. Received on Thu Oct 12 05:45:58 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Thu 12 Oct 2006 - 01:30:10 GMT.

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