assume this is what R gives me.
df1 = data.frame(grp = c("<2", "2-5", "21-26","27-32","6-10"), val= rep(0,5))
grp val
1 <2 0
2 2-5 0
3 21-26 0
4 27-32 0
5 6-10 0
but I want R to understand 6 < 21 and to give:
df2 = data.frame(grp = as.factor(c("<2", "2-5", "6-10", "21-26", "27-32")), val= rep(0,5))
grp val
1 <2 0
2 2-5 0
3 6-10 0
4 21-26 0
5 27-32 0
I tried mixedsort() from gtools but it returns indices instead of a reordered dataframe. any tips or idea how to get to this?
CodePudding user response:
you can explicit the desired levels (and force rank order) also with base R:
grp <- factor(c("<2", "2-5", "6-10", "21-26", "27-32"),
levels = c("<2", "2-5", "6-10", "21-26", "27-32"),
ordered = TRUE
)
note the use of factor
not as.factor
in this case
CodePudding user response:
It can be easily done with parse_number
to reorder the rows with arrange
library(dplyr)
df1 %>%
arrange(readr::parse_number(grp))
-output
grp val
1 <2 0
2 2-5 0
3 6-10 0
4 21-26 0
5 27-32 0