[R] Referencing factors through their equivalent numeric level

Kaushik Krishnan kaushik.s.krishnan at gmail.com
Wed May 2 18:02:11 CEST 2012


That did it! Thanks very much Berend.

On Wed, May 2, 2012 at 4:19 AM, Berend Hasselman <bhh at xs4all.nl> wrote:
>
> On 02-05-2012, at 07:22, Kaushik Krishnan wrote:
>
>> 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.
>
> Maybe this?
>
> levels(x)[y]
>
> Berend
>



-- 
Kaushik Krishnan
(kaushik.s.krishnan at gmail.com)



More information about the R-help mailing list