Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent sorting of factor levels [duplicate]

Tags:

sorting

r

When I extract the factor levels of a data frame column in R, they are automatically sorted (alphabetically). How can I prevent this? That is, I would like the order of the levels to be identical to the order present in the column of the data frame.

data.frame(Names = c("Paul McCartney", "John Lennon")) -> my.data
levels(my.data$Names)

[1] "John Lennon" "Paul McCartney"

like image 381
Sverre Avatar asked Sep 17 '25 21:09

Sverre


2 Answers

Reassign the factor after you read the data:

x <- data.frame(x=letters[c(2,1,2)], y=1:3)
x$x
## [1] b a b
## Levels: a b
x$x <- factor(x$x, levels=unique(x$x))
x$x
## [1] b a b
## Levels: b a
like image 87
Matthew Lundberg Avatar answered Sep 20 '25 12:09

Matthew Lundberg


If you want to prevent the ordering of factors you need to specifically hand the factor levels over as levels:

factor(c("Paul McCartney", "John Lennon"), levels = c("Paul McCartney", "John Lennon"))
## [1] Paul McCartney John Lennon   
## Levels: Paul McCartney John Lennon

In your case you should create the factor before you create the data.frame and paste the factor in the data.frame:

f1 <- factor(c("Paul McCartney", "John Lennon"), levels = c("Paul McCartney", "John Lennon"))
my.data <- data.frame(Names = f1)
levels(my.data$Names)

## [1] "Paul McCartney" "John Lennon" 
like image 20
Henrik Avatar answered Sep 20 '25 14:09

Henrik