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"
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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With