What is dplyr rename_with() in R?
What is tidyverse?
The tidyverse is a dogmatic collection of R packages that provides data manipulation tools, data transformation functions, data visualization, data reading from multiple packages, functional programming, and more.
It is incorporated with a wide variety of built-in packages specially designed for data science. Here are some of the more renowned packages:
- ggplot2
- tidyr
- purrr
- dplyr
- readr
- tibble
What is dplyr?
dplyr is a core package of the tidyverse in R, used for data manipulation. It has a set of predefined verbs and methods including mutate() summarize(), filter(), select(), and so on. This helps resolve common data manipulation challenges.
What is rename_with()?
The rename_with() function from the dplyr package is used to rename column names. It takes an argument function, .fn, that defines how to transform the selected columns.
Syntax
Here is the syntax for the rename_with function:
rename_with(.data, .fn, .cols = everything(), ...)
Parameters
.data: This can be a tibble, DataFrame, or a lazy DataFrame instance..fn: This shows the function to transform the selected columns..cols = everything(): These are the columns that are going to be transformed or renamed....: This is the additional argument value.
The
everything()function selects all the variables in a DataFrame or tibble.
Return value
It returns an instance of the same type as the .data argument.
Example
library("dplyr", warn.conflicts = FALSE)# loading iris dataset as tibbleiris <- as_tibble(iris)# rename all variable names to upper charactersiris <- rename_with(iris, toupper)# rename all variable names starts with Petal# replace to upper charactersdata <- rename_with(iris, tolower, starts_with("Petal"))# print updated tibble on consoleprint(data)
Explanation
- Line 3: We load the
irisdataset in the program as an R .tibble Advanced form of Data Frame in R - Line 5: The
rename_with(iris, toupper)function renames and updates the variable names of theirisdataset to upper letter case. Here, the.fnargument is thetoupperbuilt-in method to transform characters. - Line 8: In this line,
rename_with(iris, tolower, starts_with("Petal"))will update variable names to upper cases where it starts with"Petal". - Line 10: We print the updated tibble of the
irisdataset on the console.