There are a few answers mentioning the functions dplyr::rename_with
and rlang::set_names
already. By they are separate. this answer illustrates the differences between the two and the use of functions and formulas to rename columns.
rename_with
from the dplyr
package can use either a function or a formula
to rename a selection of columns given as the .cols
argument. For example passing the function name toupper
:
library(dplyr)
rename_with(head(iris), toupper, starts_with("Petal"))
Is equivalent to passing the formula ~ toupper(.x)
:
rename_with(head(iris), ~ toupper(.x), starts_with("Petal"))
When renaming all columns, you can also use set_names
from the rlang package. To make a different example, let's use paste0
as a renaming function. pasteO
takes 2 arguments, as a result there are different ways to pass the second argument depending on whether we use a function or a formula.
rlang::set_names(head(iris), paste0, "_hi")
rlang::set_names(head(iris), ~ paste0(.x, "_hi"))
The same can be achieved with rename_with
by passing the data frame as first
argument .data
, the function as second argument .fn
, all columns as third
argument .cols=everything()
and the function parameters as the fourth
argument ...
. Alternatively you can place the second, third and fourth
arguments in a formula given as the second argument.
rename_with(head(iris), paste0, everything(), "_hi")
rename_with(head(iris), ~ paste0(.x, "_hi"))
rename_with
only works with data frames. set_names
is more generic and can
also perform vector renaming
rlang::set_names(1:4, c("a", "b", "c", "d"))