/
rename_with.R
53 lines (45 loc) · 1.17 KB
/
rename_with.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#' Rename multiple columns
#'
#' @description
#' Rename multiple columns with the same transformation
#'
#' @param .df A data.table or data.frame
#' @param .fn Function to transform the names with.
#' @param .cols Columns to rename. Defaults to all columns. `tidyselect` compatible.
#' @param ... Other parameters to pass to the function
#'
#' @export
#'
#' @examples
#' df <- data.table(
#' x = 1,
#' y = 2,
#' double_x = 2,
#' double_y = 4
#' )
#'
#' df %>%
#' rename_with(toupper)
#'
#' df %>%
#' rename_with(~ toupper(.x))
#'
#' df %>%
#' rename_with(~ toupper(.x), .cols = c(x, double_x))
rename_with <- function(.df, .fn = NULL, .cols = everything(), ...) {
UseMethod("rename_with")
}
#' @export
rename_with.tidytable <- function(.df, .fn = NULL, .cols = everything(), ...) {
if (is.null(.fn)) return(.df)
.cols <- tidyselect_names(.df, {{ .cols }})
if (length(.cols) == 0) return(.df)
.fn <- as_function(.fn)
new_names <- .fn(.cols, ...)
set_col_names(.df, new_names, .cols)
}
#' @export
rename_with.data.frame <- function(.df, .fn = NULL, .cols = everything(), ...) {
.df <- as_tidytable(.df)
rename_with(.df, .fn = .fn, .cols = {{ .cols }}, ...)
}