问题
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