Re: [R] Object attributes in R

From: <dhinds_at_sonic.net>
Date: Thu 12 Oct 2006 - 22:12:17 GMT

Michael Toews <mwtoews@ucalgary.ca> wrote:

> 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[]

What I've done is to define a subclass that keeps attributes, that can be added to any object, shown below. The keep.attr() function is supposed to return just user attributes but I'm not sure if my list of special ones is complete.

I haven't looked at the performance impact of this sort of thing.

keep.attr <- function(x)
{

    a <- attributes(x)
    a[c('names','row.names','class','dim','dimnames')] <- NULL     a
}

keep <- function(x, ..., attr=NULL)
{

    cl <- union('keep', class(x))
    do.call('structure', c(list(x, class=cl, ..., attr)) }

'[.keep' <- function(x, ...) keep(NextMethod(), keep.attr(x))

'[<-.keep' <- function(x, ...) keep(NextMethod(), keep.attr(x))

tm <- keep((1:10)/10, units='sec')
ds <- keep((1:10)^2, units='cm')
dat <- data.frame(tm=tm,ds=ds)
str(dat)
tm[3:5]
ds[-3]

str(dat[1:3,])
str(dat[,1])
str(dat[1])

dat <- keep(dat, parent='xyz')
str(dat)
str(dat[2,2])

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 Fri Oct 13 08:42:04 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 - 23:30:09 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.