Re: [R] strange behavior of names<-

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

From: Gabor Grothendieck (ggrothendieck@myway.com)
Date: Mon 10 May 2004 - 14:58:49 EST


Message-id: <loom.20040510T065237-401@post.gmane.org>


Execute these two commands:
   ans <- fun(x,f)
   attributes(ans)

and you get this:

   $dim
   [1] 20

   $dimnames
   $dimnames[[1]]
[1] "a" "a" "b" "c" "a" "d" "a" "b" "d" "d" "a" "b" "d" "c" "c" "c" "b" "c" "b"
[20] "d"

so ans does not have names, it has dimnames. If you try dimnames(ans) <- NULL
then its dimnames do get nulled out.

Liaw, Andy <andy_liaw <at> merck.com> writes:

:
: 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:
:
: > 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?
:
: [BTW, this is using the tip that Thomas Lumley posted about forming the
: group means. I've wanted to write a `tsweep' function that's sort of the
: cross of tapply() and sweep().]
:
: Best,
: Andy Liaw, PhD
: Biometrics Research PO Box 2000, RY33-300
: Merck Research Labs Rahway, NJ 07065
: mailto:andy_liaw <at> merck.com 732-594-0820
:
: ______________________________________________
: R-help <at> 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
:
:

______________________________________________
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