R How to convert a numeric into factor with predifined labels

前提是你 提交于 2020-01-30 11:22:38

问题


labs = letters[3:7]
vec = rep(1:5,2)

How do I get a factor whose levels are "c" "d" "e" "f" "g" ?


回答1:


You can do something like this:

labs = letters[3:7]
vec = rep(1:5,2)
factorVec <- factor(x=vec, levels=sort(unique(vec)), labels = c( "c", "d", "e", "f", "g"))

I have sorted the unique(vec), so as to make results consistent. unique() will return unique values based on the first occurrence of the element. By specifying the order, the code becomes more robust.

Also by specifying the levels and labels both, I think that code will become more readable.

EDIT

If you look in the documentation using ?factor, you will find :

levels
an optional vector of the values (as character strings) that x might have taken. The default is the unique set of values taken by as.character(x), sorted into increasing order of x. Note that this set can be specified as smaller than sort(unique(x))

So you can note that there is some sorting inside the factor faction itself. But it is my opinion that one should add the levels information, so as to make code more readable.



来源:https://stackoverflow.com/questions/36259842/r-how-to-convert-a-numeric-into-factor-with-predifined-labels

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!