[R] Object attributes in R

Gabor Grothendieck ggrothendieck at gmail.com
Wed Oct 11 21:38:25 CEST 2006


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 at 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 at 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.
>



More information about the R-help mailing list