(Somewhat related question: Enter new column names as string in dplyr's rename function)
In the middle of a dplyr chain (%>%), I wou
Both select() and select_all() can be used to rename columns.
If you wanted to rename only specific columns you can use select:
iris %>%
select(sepal_length = Sepal.Length, sepal_width = Sepal.Width, everything()) %>%
head(2)
sepal_length sepal_width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
rename does the same thing, just without having to include everything():
iris %>%
rename(sepal_length = Sepal.Length, sepal_width = Sepal.Width) %>%
head(2)
sepal_length sepal_width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
select_all() works on all columns and can take a function as an argument:
iris %>%
select_all(tolower)
iris %>%
select_all(~gsub("\\.", "_", .))
or combining the two:
iris %>%
select_all(~gsub("\\.", "_", tolower(.))) %>%
head(2)
sepal_length sepal_width petal_length petal_width species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa