[R] Sorting based a custom sorting function
Martin Møller Skarbiniks Pedersen
tr@xp|@yer @end|ng |rom gm@||@com
Thu Dec 14 09:00:12 CET 2023
Hi,
I need to sort a data.frame based on a custom sorting function.
It is easy in many languages but I can't find a way to do it in R.
In many cases I could just use an ordered factor but my data.frame
contains poker hands and
I need to rank these hands. I already got a function that compares two hands.
Here is a MRE (Minimal, Reproducible Example):
df <- data.frame(person = c("Alice", "Bob", "Charlie"), value =
c("Medium", "Small", "Large"))
# 0 means equal, -1 means left before right, 1 means right before left
custom_sort <- function(left, right) {
if (left == right) return(0)
if (left == "Small") return(-1)
if (left == "Medium" & right == "Large") return(-1)
return(1)
}
# sort df according to custom_soft
# expect output is a data.frame:
# name size
# 1 Bob Medium
# 2 Alice Small
# 3 Charlie Large
In this simple case I can just use an ordered factor but what about
the poker hands situation?
Regards
Martin
More information about the R-help
mailing list