gogo88
gogo88

Reputation: 309

replace at once multiple columns names which end with different patterns in R

I have a table with hundreds of columns. Their names end either with .a or .b What I need is to rename all columns.a with a columns.a_new and column.b with column->column.b_new at once.

I can do it only one pattern at a time but I don't know how to do it at once for all columns.

rename_at_example <- my_table %>% rename_at(vars(ends_with(".a")), 
funs(str_replace(., ".a", ".a_new")))

Any idea how to write it in a compact way for all columns? Thank you

Upvotes: 0

Views: 234

Answers (2)

IceCreamToucan
IceCreamToucan

Reputation: 28705

If '.a' names and '.b' names don't require the same replacement/action, e.g. adding '_new' to the end, you could use reduce2

library(tidyverse) # dplyr + purrr for reduce2

df <- data.frame(one.a = 1, one.d = 2, twoa = 3, two.b = 4, three.a = 5)
df
#   one.a one.d twoa two.b three.a
# 1     1     2    3     4       5

df %>% 
  rename_all(~ reduce2(c('\\.a$', '\\.b$'),  c('.a_new1', '.b_new2'), 
                       str_replace, .init = .x))

#   one.a_new1 one.d twoa two.b_new2 three.a_new1
# 1          1     2    3          4            5

Upvotes: 1

tmfmnk
tmfmnk

Reputation: 40171

One dplyr option could be:

df %>%
 rename_at(vars(matches("[ab]$")), ~ paste0(., "_new"))

   col1a_new col2a_new col1b_new col2b_new col1c col2c
1          1        11         1        11     1    11
2          2        12         2        12     2    12
3          3        13         3        13     3    13
4          4        14         4        14     4    14
5          5        15         5        15     5    15
6          6        16         6        16     6    16
7          7        17         7        17     7    17
8          8        18         8        18     8    18
9          9        19         9        19     9    19
10        10        20        10        20    10    20

Sample data:

df <- data.frame(col1a = 1:10,
                 col2a = 11:20,
                 col1b = 1:10,
                 col2b = 11:20,
                 col1c = 1:10,
                 col2c = 11:20,
                 stringsAsFactors = FALSE)

Upvotes: 2

Related Questions