[R] Object attributes in R

Frank E Harrell Jr f.harrell at vanderbilt.edu
Thu Oct 12 02:18:18 CEST 2006


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

This has been a tricky issue and for a long time I've wanted a system 
option( ) that would specify attributes that automatically survive 
subscripting.  Since we don't have that, I have [. methods for objects 
with label and/or units attributes in the Hmisc package.


-- 
Frank E Harrell Jr   Professor and Chair           School of Medicine
                      Department of Biostatistics   Vanderbilt University



More information about the R-help mailing list