I have data that I read into a dataframe specifying colClasses
, e.g.:
dat <- read.table(textConnection("
One Two
D 1
B 2
A 3
C 4
"), header = TRUE, colClasses = c("factor", "integer"))
If levels aren’t specified, R orders them alphabetically:
str(dat)
'data.frame': 4 obs. of 2 variables:
$ One: Factor w/ 4 levels "A","B","C","D": 4 2 1 3
$ Two: int 1 2 3 4
If I want the levels to be in a different order, for example in the order the values appear –
$ One: Factor w/ 4 levels "D","B","A","C": 1 2 3 4
– how can I specify this in the command that reads in the data?
I do not want to reorder the levels!!
I do not want to do:
dat$One <- factor(dat$One, levels = c("D","B","A","C"))
New contributor
Ben is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.