Package: purrr


Function: set_names()


1. Change all variable names to upper case

Review the data (d1)

# A tibble: 3 x 3
  Var1   Var2  Var3
  <chr> <dbl> <dbl>
1 a         2   3.6
2 b        NA   8.5
3 c         3  NA  

Change all variable names to upper by adding the base::toupper() function

  • Note: You can also change all variable names to lower using base::tolower() function.
d1 %>% 
  purrr::set_names(., base::toupper)
# A tibble: 3 x 3
  VAR1   VAR2  VAR3
  <chr> <dbl> <dbl>
1 a         2   3.6
2 b        NA   8.5
3 c         3  NA  
  • Note: There several other functions that convert strings to upper or lower including stringr::str_to_lower() and stringr::str_to_upper().
d1 %>% 
  purrr::set_names(., stringr::str_to_upper)
# A tibble: 3 x 3
  VAR1   VAR2  VAR3
  <chr> <dbl> <dbl>
1 a         2   3.6
2 b        NA   8.5
3 c         3  NA  

Package: dplyr


Function: rename_with()


1. Change all variable names to lower case

Review the data (d1)

# A tibble: 3 x 3
  Var1   Var2  Var3
  <chr> <dbl> <dbl>
1 a         2   3.6
2 b        NA   8.5
3 c         3  NA  

Change all variable names to lower by adding the base::tolower() function

d1 %>% 
  dplyr::rename_with(., tolower)
# A tibble: 3 x 3
  var1   var2  var3
  <chr> <dbl> <dbl>
1 a         2   3.6
2 b        NA   8.5
3 c         3  NA  

Package: janitor


Function: clean_names()


1. Change all variable names to snake_case (lower case and underscore to separate words)

Review the data (d1)

# A tibble: 3 x 3
  `Var 1` `Var 2` `Var 3`
  <chr>     <dbl>   <dbl>
1 a             1       2
2 b          -999       0
3 c             3    -999

Change the variable names to snake_case (the default for janitor::clean_names())

d3 %>% 
  janitor::clean_names()
# A tibble: 3 x 3
  var_1 var_2 var_3
  <chr> <dbl> <dbl>
1 a         1     2
2 b      -999     0
3 c         3  -999

2. Change all variable names to UpperCamelCase (no spaces, indicating word separation through capital letters)

Review the data (d1)

# A tibble: 3 x 3
  stu_id stu_gender `lunch status`
  <chr>  <chr>      <chr>         
1 a      m          f             
2 b      f          r             
3 c      n          p             

Change the variable names to UpperCamelCase

  • Note: Here we can simply add the argument case = “upper_camel”. To see all of the case options type ?to_any_case in the console.
d4 %>% 
  janitor::clean_names(., case = "upper_camel")
# A tibble: 3 x 3
  StuId StuGender LunchStatus
  <chr> <chr>     <chr>      
1 a     m         f          
2 b     f         r          
3 c     n         p          

Return to Name Variables