Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
993 views
in Technique[技术] by (71.8m points)

r - Reorder factor levels using names

I can reorder the levels of a factor using their indices like this

factor(iris$Species,levels(iris$Species)[c(3:1)])

However if I try to reorder the same factor by name, it does not work:

factor(iris$Species,levels(iris$Species)[c("virginica", "versicolor", "setosa")])

Is there a way to reorder the levels of a factor using their names?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why don't you use the basic variant with giving new level names:

factor(iris$Species, levels=c("virginica", "versicolor", "setosa"))

Be sure to list all level names, though. Otherwise, you will end up with NA values.

However, for completeness: If you rely on the order of the elements within a factor, you probably should used ordered instead of factor. That is just a factor with, well, ordered levels, or, more mathematically, a relation < between the factor levels. See:

> ordered(1:3, levels=c('1', '3', '2'))
[1] 1 2 3
Levels: 1 < 3 < 2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...