Re: [R] strange behavior of names<-

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

From: Prof Brian Ripley (ripley@stats.ox.ac.uk)
Date: Mon 10 May 2004 - 16:21:55 EST


Message-id: <Pine.LNX.4.44.0405100717080.8309-100000@gannet.stats>

Remember tapply with a single factor in R returns a 1D array. What you
are seeing are the dimnames, not the names: look at attributes() on your
return value (or even name() or str() on it).

I suspect you intended an as.vector() call in the formation of m.

Brian

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

> 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:
>
> > x = rnorm(20)
> > f = factor(sample(rep(letters[1:4], 5)))
> > fun(x, f)
> a b c b c c
> d
> -0.53791639 1.03704065 0.95727411 0.89219177 -0.04218746 0.57976675
> -2.15799919
> a c d a d b
> d
> 1.28422452 -0.92881186 0.40526262 -0.13471983 -0.72599709 1.68726680
> -0.95420354
> a c a b b d
> -2.28013373 1.02522037 0.07728352 0.54321899 0.95742354 -1.68420455
>
> What am I missing?

-- 
Brian D. Ripley,                  ripley@stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

______________________________________________ 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