Reputation: 150
T
-----
2016m1
2016m10
2016m11
2016m12
2016m2
2016m3
2016m4
2016m5
2016m6
2016m7
2016m8
2016m9
I want to arrange this table, like table below.
T
-----
2016m1
2016m2
2016m3
2016m4
2016m5
2016m6
2016m7
2016m8
2016m9
2016m10
2016m11
2016m12
So anybody can help me ?
Upvotes: 1
Views: 59
Reputation: 483
Using regex
with gsub
is something like this:
Assuming that T
is a data.frame
last_digits <- as.numeric(gsub("[0-9]{4}m","",T[,1]))
T[order(last_digits),] #Ordered dataframe
Regex explanation
[0-9]{4}m
Looks for exactly 4 digits, if you want to use a range of numbers you can use {num_1-num_2}
, after finding the "rule" then it will look for the letter m
.
Upvotes: 1
Reputation: 156
Or using base-R where your data vector is T:
T[order(sapply(T, function(l) as.integer(substr(l, 6, nchar(l)+1))))]
Upvotes: 1
Reputation: 18661
With mixedsort
from gtools
:
library(gtools)
df$T <- mixedsort(df$T)
or mixedorder
:
df$T <- df$T[mixedorder(df$T)]
Output:
T
1 2016m1
2 2016m2
3 2016m3
4 2016m4
5 2016m5
6 2016m6
7 2016m7
8 2016m8
9 2016m9
10 2016m10
11 2016m11
12 2016m12
Data:
df <- structure(list(T = c("2016m1", "2016m10", "2016m11", "2016m12",
"2016m2", "2016m3", "2016m4", "2016m5", "2016m6", "2016m7", "2016m8",
"2016m9")), .Names = "T", class = "data.frame", row.names = c(NA,
-12L))
Upvotes: 3