[R] Object attributes in R

Michael Toews mwtoews at ucalgary.ca
Wed Oct 11 21:18:20 CEST 2006


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



More information about the R-help mailing list