Kaushik Krishnan
2012-May-02 05:22 UTC
[R] Referencing factors through their equivalent numeric level
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)
Berend Hasselman
2012-May-02 11:19 UTC
[R] Referencing factors through their equivalent numeric level
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
Reasonably Related Threads
- Issue with %in% - not matching identical rows in data frames
- User input when running R code in batch mode
- Equivalent of XenBus for fully-virtualized Xen
- (PR#1964) The attached function working fine with R 1.3.0 but giving problem with R 1.5.1 (PR#1964)
- Pull data from Tally 9.1 to R studio