-
Notifications
You must be signed in to change notification settings - Fork 16
Create New Variables
Cghlewis edited this page Jan 31, 2023
·
64 revisions
There are endless reasons why you may need to create a new variable. Some examples are:
- Create an ID variable
- Create an indicator variable based on one or more existing variables in your data
- Ex: control/treatment or at-risk/not at-risk
- Calculate a rowwise summary score
- Recoding or collapsing categories of existing variables into a new variable
The most common function for creating new (and updating existing) variables in a tidyverse
fashion is dplyr::mutate()
. You will see examples of this function being used throughout almost all scenarios in this resource. Almost any time you recode, create, change class, etc., you will be using the dplyr::mutate()
function. Although there are a few other ways I will demonstrate to add columns.
- Add a random ID variable (See Randomize)
- Calculate an age variable
- [Calculate a row sum or mean score](See Calculate Row Values)
- Create a correct/incorrect score variable
- Create multiple correct/incorrect score variables
- Create dummy coded variables from a single variable
- Create a preassigned treatment variable
- Create an at-risk indicator variable
- [Create a completion indicator variable](See Select Variables)
Main functions used in examples
Package | Functions |
---|---|
dplyr | mutate() |
tidyr | pivot_wider() |
tibble | add_column() |
Other functions used in examples
Package | Functions |
---|---|
dplyr | case_when(); across(); select(); if_else() |
stringr | str_count(); str_detect() |
tidyselect | contains() |
janitor | clean_names() |
lubridate | interval() |
base | months(); round(); ceiling(); as.numeric() |
tidyr | separate_rows() |
Resources
- https://cran.r-project.org/web/packages/stringr/vignettes/regular-expressions.html
- https://data.library.virginia.edu/working-with-dates-and-time-in-r-using-the-lubridate-package/
- https://r4ds.had.co.nz/dates-and-times.html
- https://cran.r-project.org/web/packages/lubridate/vignettes/lubridate.html
- https://www.tidyverse.org/blog/2019/06/rlang-0-4-0/