Package: purrr


Function: set_names()


1. Set all variable names.

Review the data (d7)

  • Note: In this example you had a file, such as a csv file, with no variable names. You’ll see that when you read the file in, R assigned variable names of X1, X2 and X3 in this instance.
# A tibble: 3 x 3
  X1       X2    X3
  <chr> <dbl> <dbl>
1 a         2   3.6
2 b        NA   8.5
3 c         3  NA  

You can review the variable names using base::names().

names(d7)
[1] "X1" "X2" "X3"

Add variable names

  • Note: For this function you provide a vector of names to be applied. Quotes are required around variable names and the number of variable names given must be equal to the number of variables in the data frame.

  • Note: Pay attention to the order of your variables and names. While using purrr::set_names() is a convenient way to name variables without having to enter as much information as you would in the dplyr::rename() function, it can cause problems if you end up renaming variables incorrectly because you were unsure of the variable order.

d7 %>% 
  purrr::set_names("id", "grade", "test1")
# A tibble: 3 x 3
  id    grade test1
  <chr> <dbl> <dbl>
1 a         2   3.6
2 b        NA   8.5
3 c         3  NA  

Return to Name Variables