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).

# View the names
names(mydat)
##  [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).

# Suppose dat3 has  variables
names(dat3) <- c("name1", "name2", "name3")

In tidyverse, use rename(New_Name = Old_Name):

mydat_tibble <- mydat_tibble %>% 
  rename(Years_From_Diagnosis = Yrs_From_Dx)

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.