[R] strange behavior of names<-
Prof Brian Ripley
ripley at stats.ox.ac.uk
Mon May 10 08:21:55 CEST 2004
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 at 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
More information about the R-help
mailing list