[R] Factor names & levels
Gabor Grothendieck
ggrothendieck at myway.com
Mon Dec 22 02:02:20 CET 2003
The effect of names() on factors is undefined. The fact
that it coincidentally partially works on factors is just
chance.
For it to be well defined, there would need to be a names
method and a names<- method for the factor class or else
the default methods would have to be able to handle factors.
Its a bit dangerous to rely on the coincidental behavior of
functionality, but in the absence of explicit R support, if
using names with factors were important to you then you could
define your own methods like this:
"names<-.factor" <- function( x, value ) {
attr(x, "levels") <- value
x
}
names.factor <- function(x) attr( x, "levels" )
# with the above, this works:
x <- factor(c("one","three"))
names(x) <- c("fred","jim") # implicitly invokes "names<-.factor"
names(x) # implicitly invokes names.factor
Hope this clears it up for you.
---
Date: Mon, 22 Dec 2003 00:38:14 +0000 (GMT)
From: Damon Wischik <djw1005 at cam.ac.uk>
To: Gabor Grothendieck <ggrothendieck at myway.com>
Cc: <R-help at stat.math.ethz.ch>
Subject: Re: [R] Factor names & levels
> I agree it may not be 100% clear but ?names does say
> "The default methods get and set the '"names"' attribute
> of a vector or list." and if you issue the command:
> methods("names")
> you find that the only non-default method is names.dist.
I still want to know how I should understand the following:
> x <- factor(c("one","three"))
> names(x) <- c("fred","jim")
> names(x)
[1] "fred" "jim"
class(x)
[1] "factor"
Given that names seems to work on factors, I can see two possibilities:
1. It is a bug that it acts as it does;
2. the default method does what it says in the help page, but also does
more than just this.
I don't know enough to look at the source code to find out what is going
on.
Damon.
More information about the R-help
mailing list