[R] Object attributes in R

dhinds at sonic.net dhinds at sonic.net
Fri Oct 13 00:12:17 CEST 2006


Michael Toews <mwtoews at 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.

-- David Hinds

----------------

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



More information about the R-help mailing list