[R] Referencing factors through their equivalent numeric level
Kaushik Krishnan
kaushik.s.krishnan at gmail.com
Wed May 2 07:22:16 CEST 2012
Hey folks
I'm sorry for bringing what must be a very simple question to R-help,
but after some research I haven't been able to find a solution to my
problem.
Suppose I create a simple factor:
[code]
> x<-c("A","B","B","C","A")
> x
[1] "A" "B" "B" "C" "A"
> x <- as.factor(x)
> x
[1] A B B C A
Levels: A B C
[/code]
Now, when I see this factor in terms of its numeric level values, I get
[code]
> as.numeric(x)
[1] 1 2 2 3 1
[/code]
Suppose I have
[code]
y <- 2
[/code]
I want the numeric value of y to reference the level of factor x. That
is, I am looking for a function (`foo') so that I will get the
following
[code]
foo(y) #or maybe foo(y,x)
[1] B
[/code]
I can think of a roundabout way of doing through a user defined
function, but I am sure that there is a built-in function that offers
this functionality. I'd be grateful if someone could tell me what that
function is.
Thanks in advance
--
Kaushik Krishnan
(kaushik.s.krishnan at gmail.com)
More information about the R-help
mailing list