Re: [R] Object attributes in R

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

Michael Toews <> 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))'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)


dat <- keep(dat, parent='xyz')
str(dat[2,2]) mailing list PLEASE do read the posting guide 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 Please read the posting guide before posting to the list.