[R] subsetting without losing the attributes
ehlers at ucalgary.ca
Wed Jul 18 02:03:10 CEST 2012
On 2012-07-17 04:16, MK wrote:
> How do I use the subset function without losing the attributes?
You don't. At least not without modifying subset.data.frame().
The key sentence on the ?Extract help page is this:
"Subsetting (except by an empty index) will drop all
attributes except names, dim and dimnames."
(This should probably say "... by an empty _first_ index ...")
If you really want a subset function to do what you want then
it's an easy modification; just replace the last line of
x[, vars, drop = drop]
x[r, vars, drop = drop]
But this still won't let you pick subsets of rows without
losing the attributes. So I see no advantage over [,].
I would just save the attributes and reassign them.
> For example,
> test.df <- data.frame(a = rnorm(100), b = runif(100), c = rexp(100))
> attr(test.df[, 1], "units") <- c("cm")
> attr(test.df[, 2], "units") <- c("kg")
> attr(test.df[, 3], "units") <- c("ha")
> ## We want this behavior
> str(test.df[, "a", drop = FALSE])
> ## But not the behavior of subset
> str(subset(test.df, select = a, drop = FALSE))
> ## Whic is equivalent to
> str(test.df[TRUE, "a", drop = FALSE])
> R-help at r-project.org mailing list
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help