[R] strange behavior of names<-

Thomas Lumley tlumley at u.washington.edu
Mon May 10 15:56:28 CEST 2004


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




More information about the R-help mailing list