Convert factors to numbers
[This article was first published on Quantitative Ecology, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
If you have a vector of factors it is easy to get the factor level; however, I always forget how to extract the factor value. I ran into the answer here.Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
> x<-factor(c(round(rnorm(10),2),"A","B",NA)) > x [1] 1.61 1.12 1.26 0.09 -0.13 0.16 -0.03 -0.1 0.09 -0.47 [11] A B Levels: -0.03 0.09 -0.1 -0.13 0.16 -0.47 1.12 1.26 1.61 A B > as.numeric(x) [1] 9 7 8 2 4 5 1 3 2 6 10 11 NA > as.numeric(levels(x)[x]) [1] 1.61 1.12 1.26 0.09 -0.13 0.16 -0.03 -0.10 0.09 -0.47 [11] NA NA NA Warning message: NAs introduced by coercion
**UPDATE**
And another method mentioned in the comments (that I like better):
> as.numeric(as.character(x))
To leave a comment for the author, please follow the link and comment on their blog: Quantitative Ecology.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.