-
Notifications
You must be signed in to change notification settings - Fork 16
Name Variables
Cghlewis edited this page Jan 30, 2023
·
12 revisions
These functions help you name or rename your variables for the following types of situations.
- You have data with no column names and if you do not assign variable names, R will add default column names such as X1, X2, X3 and so on.
- You have data with nonsensical variable names and need to rename them for clarity.
- You may want to rename your variables to make them more descriptive, shorter, remove special characters or spaces, or to concatenate a prefix or suffix to your variables.
The following examples cover common variable naming, renaming, and cleaning functions you can use.
Some variable naming best practices are to make variable names:
- Short but descriptive
- No spaces between words
- No special characters included
Common variable naming styles:
- snake_case
- SCREAMING_SNAKE_CASE
- UpperCamelCase or PascalCase
- camelCase
- kebab-case
- Set all variable names
- Rename specified variables
- Rename variables in a select statement
- Name variables using a data dictionary
Main functions used in examples
Package | Functions |
---|---|
purrr | set_names() |
dplyr | rename(); rename_with() |
janitor | clean_names() |
Other functions used in examples
Package | Functions |
---|---|
base | names(); paste0(); toupper(); tolower() |
tidyselect | all_of(); contains() |
stringr | str_replace(); str_remove(); str_to_upper(); str_c() |
tibble | deframe() |
readxl | read_excel() |
Resources
- http://kbroman.org/dataorg/pages/names.html
- https://twitter.com/allison_horst/status/1205702878544875521/photo/1
- https://cran.r-project.org/web/packages/janitor/vignettes/janitor.html#clean-data.frame-names-with-clean_names
- https://dplyr.tidyverse.org/reference/select.html
- https://dplyr.tidyverse.org/reference/rename.html
- https://cran.r-project.org/web/packages/stringr/vignettes/regular-expressions.html
- https://github.com/rstudio/cheatsheets/blob/master/strings.pdf
- https://www.tidyverse.org/blog/2020/03/dplyr-1-0-0-select-rename-relocate/
- https://www.mattroumaya.com/post/52-different-ways-to-rename-a-column-in-r/
- https://tidyselect.r-lib.org/reference/faq-external-vector.html