Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming multiple columns from vector in dplyr chain

Tags:

r

dplyr

I have a dataframe that I would like to rename several columns with similar name conventions (e.g., starts with "X") and/or column positions (e.g., 4:7). The new names of the columns are stored in a vector. How do I rename this columns in a dplyr chain?

# data
df <- tibble(RID = 1,Var1 = "A", Var2 = "B",old_name1 =4, old_name2 = 8, old_name3=20)
new_names <- c("new_name1","new_name2","new_name3")

#psuedo code
df %>%
  rename_if(starts_with('old_name'), new_names)
like image 547
Jeff Parker Avatar asked Sep 10 '25 07:09

Jeff Parker


1 Answers

An option with rename_at would be

df %>% 
  rename_at(vars(starts_with('old_name')), ~ new_names)
# A tibble: 1 x 6
#    RID Var1  Var2  new_name1 new_name2 new_name3
#   <dbl> <chr> <chr>     <dbl>     <dbl>     <dbl>
#1  1.00 A     B          4.00      8.00      20.0

But, it is possible to make a function that works with rename_if by creating a logical index on the column names

df %>%
    rename_if(grepl("^old_name", names(.)), ~ new_names)
# A tibble: 1 x 6
#    RID Var1  Var2  new_name1 new_name2 new_name3
#  <dbl> <chr> <chr>     <dbl>     <dbl>     <dbl>
#1  1.00 A     B          4.00      8.00      20.0

The rename_if in general is checking at the values of the columns instead of the column names i.e.

new_names2 <- c('var1', 'var2')
df %>%
     rename_if(is.character, ~ new_names2)
# A tibble: 1 x 6
#    RID var1  var2  old_name1 old_name2 old_name3
#   <dbl> <chr> <chr>     <dbl>     <dbl>     <dbl>
#1  1.00 A     B          4.00      8.00      20.0
like image 96
akrun Avatar answered Sep 12 '25 21:09

akrun