3.8 Rename variables
You can rename a variable in a dataset by changing a value in the names()
vector (base R) or by using the rename()
function (tidyverse).
## [1] "ID" "Age" "AgeGp" "Sex"
## [5] "Yrs_From_Dx" "CDAI" "CDAI_YN" "DAS_28"
## [9] "DAS28_YN" "Steroids_GT_5" "DMARDs" "Biologics"
## [13] "sDMARDS" "OsteopScreen" "FIPS" "Sex_orig"
## [17] "AgeGp_orig" "AgeGp2" "Yrs_From_Dx_2" "log_Yrs_From_Dx"
## [21] "elderly" "elderly_fac" "AgeGroup"
# Change Yrs_From_Dx to Years_From_Diagnosis
names(mydat)[names(mydat) == "Yrs_From_Dx"] <- "Years_From_Diagnosis"
# View the new names
names(mydat)
## [1] "ID" "Age" "AgeGp"
## [4] "Sex" "Years_From_Diagnosis" "CDAI"
## [7] "CDAI_YN" "DAS_28" "DAS28_YN"
## [10] "Steroids_GT_5" "DMARDs" "Biologics"
## [13] "sDMARDS" "OsteopScreen" "FIPS"
## [16] "Sex_orig" "AgeGp_orig" "AgeGp2"
## [19] "Yrs_From_Dx_2" "log_Yrs_From_Dx" "elderly"
## [22] "elderly_fac" "AgeGroup"
To rename all the variables, assign a vector of names (which means that for variable names you do not wish to rename, you must specify the existing name).
In tidyverse
, use rename(New_Name = Old_Name)
:
rename()
overwrites an existing variable. If you used mutate()
instead of rename()
above, then you would create a new, additional, variable that is a copy of the old one and the old one would remain, as well.