Reputation: 609
I have a data.frame that looks like this:
320 Dutch A7 3
321 Dutch A8 3
322 Dutch A9 4
323 Dutch A10 1
324 Dutch A11 4
327 Dutch A14 4
325 Dutch A12 3
328 Dutch A15 10
326 Dutch A13 1
329 Dutch A16 3
How can I order it so all the A1, A2, etc.
are in order alphabetically and numerically, so that I get:
320 Dutch A7 3
321 Dutch A8 3
322 Dutch A9 4
323 Dutch A10 1
324 Dutch A11 4
325 Dutch A12 3
326 Dutch A13 1
327 Dutch A14 4
328 Dutch A15 10
329 Dutch A16 3
Thank you!
Upvotes: 0
Views: 1604
Reputation: 121077
Forget the data frame part for now. Here's a sample vector that you want to order
x <- paste(
rep.int(LETTERS[1:3], 16),
rep.int(1:16, 3),
sep = ""
)
y <- sample(x)
Just calling sort(y)
won't work because number get sorted into lexographical order, so you get something like A1, A10, A11, ...
Instead, use substring
to split the column into a letter and a number.
indexer <- data.frame(
letter = substring(y, 1, 1),
number = as.numeric(substring(y, 2))
)
Then, as aL3xa suggested, call order
to order the resulting data frame.
o <- with(indexer, order(letter, number))
y[o]
To get this to work with a data frame, simply replace y
with your_data$index_column
.
Upvotes: 1