Re: [R] strange behavior of names<-

About this list Date view Thread view Subject view Author view Attachment view

From: Thomas Lumley (tlumley@u.washington.edu)
Date: Mon 10 May 2004 - 23:56:28 EST


Message-id: <Pine.A41.4.58.0405100654060.93038@homer40.u.washington.edu>

On Sun, 9 May 2004, Liaw, Andy wrote:

> Dear R-help,
>
> I've encounter what seems to me a strange problem with "names<-". Suppose I
> define the function:
>
> fun <- function(x, f) {
> m <- tapply(x, f, mean)
> ans <- x - m[match(f, unique(f))]
> names(ans) <- names(x)
> ans
> }
>
> which subtract out the means of `x' grouped by `f' (which is the same as,
> e.g., resid(lm(x~f)) if `f' is a factor). If `x' does not have names, then
> I'd expect the output of the function not to have names, as names(x) would
> be NULL, and assigning NULL to names(ans) should wipe out the names of
> `ans'. However, I get:

That's because ans is a 1-d matrix, not a vector. If you want ans to be a
vector you need
        ans <- as.vector(x-m[match(f, unique(f))])
        names(ans)<-names(x)

        -thomas

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html


About this list Date view Thread view Subject view Author view Attachment view

This archive was generated by hypermail 2.1.3 : Mon 31 May 2004 - 23:05:08 EST