You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In javascript, there is a built-in function Array.prototype.sort() that works on an array (like an R list) and takes a user-defined binary function to define ordering.
my_array.sort((a,b)=>some_function(a,b))
Base R functions sort and order accept atomic vectors only. To sort lists, the user needs to use a combination of indexing with [ and order on some expression. For example, imagine we wanted to sort a list of vectors by length...
The proposed purrr function would sort a list based on a user-provided function to determine precedence.
# accept a binary function for complex comparisonssorted_x<- sort_list(.x=x, .f= \(a,b) length(a) < length(b))
# accept a unary function that evaluates to a `sort`-able atomic vectorsorted_x<- sort_list(x, .f= \(a) length(a))
This is a reprex to illustrate a simple implementation and use case.
# very minimal implementation of proposed function using quicksortsort_list<-function(.x, .f) {
if (length(.x) <=1) return(.x)
if (length(formals(.f)) ==1) return(.x[order(sapply(.x, .f))])
pivot<-.x[[1]]
items<-.x[-1]
has_precedence<- vapply(items, \(item) .f(item, pivot), logical(1L))
before<- sort_list(items[which(has_precedence)], .f)
after<- sort_list(items[which(!has_precedence)], .f)
c(before, list(pivot), after)
}
# eg, say need to sort a list of vectors by lengthx<-list(letters, letters[1:2], letters[1:4], LETTERS)
# use proposed function to sort listx|> sort_list(\(a, b) length(a) < length(b))
x|> sort_list(\(a) length(a))
Thanks for your consideration! I'm a huge fan of purrr and tidyverse.
The text was updated successfully, but these errors were encountered:
In javascript, there is a built-in function Array.prototype.sort() that works on an array (like an R list) and takes a user-defined binary function to define ordering.
Base R functions
sort
andorder
accept atomic vectors only. To sort lists, the user needs to use a combination of indexing with[
andorder
on some expression. For example, imagine we wanted to sort a list of vectors by length...The tidy approach could use
dplyr::arrange
on a tibble to sort the list-column.The proposed purrr function would sort a list based on a user-provided function to determine precedence.
This is a reprex to illustrate a simple implementation and use case.
Thanks for your consideration! I'm a huge fan of purrr and tidyverse.
The text was updated successfully, but these errors were encountered: