/R/select_helpers.R

https://github.com/TysonStanley/tidyfast · R · 54 lines · 16 code · 7 blank · 31 comment · 0 complexity · d2cdd22b73d5848b6f76b2fb8dde7e0a MD5 · raw file

  1. #' Select helpers
  2. #'
  3. #' @description
  4. #' These functions allow you to select variables based on their names.
  5. #'
  6. #' * `dt_starts_with()`: Starts with a prefix
  7. #' * `dt_starts_with()`: Ends with a suffix
  8. #' * `dt_contains()`: Contains a literal string
  9. #' * `dt_everything()`: Matches all variables
  10. #'
  11. #' @param match a character string to match to variable names
  12. #'
  13. #' @return None. To be used within the `dt_pivot_*` functions.
  14. #'
  15. #' @md
  16. #' @examples
  17. #' library(data.table)
  18. #'
  19. #' # example of using it with `dt_pivot_longer()`
  20. #' df <- data.table(row = 1, var = c("x", "y"), a = 1:2, b = 3:4)
  21. #' pv <- dt_pivot_wider(df,
  22. #' names_from = var,
  23. #' values_from = c(dt_starts_with("a"), dt_ends_with("b"))
  24. #' )
  25. #' @export
  26. dt_starts_with <- function(match) {
  27. .names <- names(parent.frame())
  28. seq_along(.names)[startsWith(.names, match)]
  29. }
  30. #' @export
  31. #' @rdname dt_starts_with
  32. dt_contains <- function(match) {
  33. .names <- names(parent.frame())
  34. seq_along(.names)[grepl(match, .names)]
  35. }
  36. #' @export
  37. #' @rdname dt_starts_with
  38. dt_ends_with <- function(match) {
  39. .names <- names(parent.frame())
  40. seq_along(.names)[endsWith(.names, match)]
  41. }
  42. #' @export
  43. #' @rdname dt_starts_with
  44. dt_everything <- function() {
  45. .names <- names(parent.frame())
  46. seq_along(.names)
  47. }