I have the following tibble:
library(tidyverse)
df <- structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5), Sepal.Width = c(3.5,
3, 3.2, 3.1, 3.6), Pet
You can use the rename_at() function for this (starting in dplyr_0.7.0) or rename_with() (starting in dplyr_1.0.0).
For example, you can pass the variables you want to rename as strings. In your example, the paste0 function can be used to append on the appropriate suffix to each column.
cols = c("Sepal.Length", "Petal.Length")
to_app = ".xxx"
For dplyr_1.0.0, use rename_with(). The function argument comes before the column argument. You can use the tidy-select function all_of() (or others) to choose columns.
rename_with(df, .fn = ~paste0(., to_app), .cols = all_of(cols) )
# A tibble: 5 x 3
Sepal.Length.xxx Sepal.Width Petal.Length.xxx
*
1 5.1 3.5 1.4
2 4.9 3 1.4
3 4.7 3.2 1.3
4 4.6 3.1 1.5
5 5 3.6 1.4
Earlier versions of dplyr use rename_at(). This has been superseded in version 1.0.0, which means there are new functions to use as above but this particular function is not going away.
rename_at(df, cols, list( ~paste0(., to_app) ) )
# A tibble: 5 x 3
Sepal.Length.xxx Sepal.Width Petal.Length.xxx
*
1 5.1 3.5 1.4
2 4.9 3.0 1.4
3 4.7 3.2 1.3
4 4.6 3.1 1.5
5 5.0 3.6 1.4
You can also use the select helper functions to choose variables for renaming, such as contains.
rename_at(df, vars( contains("Length") ), list( ~paste0(., ".xxx") ) )
# A tibble: 5 x 3
Sepal.Length.xxx Sepal.Width Petal.Length.xxx
*
1 5.1 3.5 1.4
2 4.9 3.0 1.4
3 4.7 3.2 1.3
4 4.6 3.1 1.5
5 5.0 3.6 1.4
This list() coding replaces the previous funs() coding starting in dplyr_0.7.0. Previously, e.g., funs( paste0(., to_app) )