[R] subsetting without losing the attributes
Rui Barradas
ruipbarradas at sapo.pt
Wed Jul 18 09:23:55 CEST 2012
Hello,
Another quote from the help pages that could be usefull is, from ?subset,
Warning
This is a convenience function intended for use interactively. For
programming it is better to use the standard subsetting functions like
[, and in particular the non-standard evaluation of argument subset can
have unanticipated consequences.
So if the op wants a behavior that can be seen with `[`, use the
recommended extractor function.
Hope this helps,
Rui Barradas
Em 18-07-2012 01:03, Peter Ehlers escreveu:
> Inline
>
> On 2012-07-17 04:16, MK wrote:
>> Hi,
>>
>> 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
> subset.data.frame with
>
> if(isTRUE(r))
> x[, vars, drop = drop]
> else
> 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.
>
> Peter Ehlers
>
>>
>> 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])
>>
>> Cheers,
>> M
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> 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
mailing list