1

I want to rename multiple columns that starts with the same string. However, all the codes I tried did not change the columns.

For example this:

df %>% rename_at(vars(matches('^oldname,\\d+$')), ~ str_replace(., 'oldname', 'newname'))

And also this:

df %>% rename_at(vars(starts_with(oldname)), funs(sub(oldname, newname, .))

Are you familiar with a suitable code for rename?

Thank you!

Darren Tsai
  • 32,117
  • 5
  • 21
  • 51
Reut Zabag
  • 21
  • 1
  • Hi, if your question has been solved, please select one of the answers you prefer as accepted by clicking the check mark next to it. Thanks! – Darren Tsai May 14 '22 at 11:38

1 Answers1

1

Take iris for example, you can use rename_with() to replace those column names started with "Petal" with a new string.

head(iris) %>%
  rename_with(~ sub("^Petal", "New", .x), starts_with("Petal"))

  Sepal.Length Sepal.Width New.Length New.Width Species
1          5.1         3.5        1.4       0.2  setosa
2          4.9         3.0        1.4       0.2  setosa
3          4.7         3.2        1.3       0.2  setosa
4          4.6         3.1        1.5       0.2  setosa
5          5.0         3.6        1.4       0.2  setosa
6          5.4         3.9        1.7       0.4  setosa

You can also use rename_at() in this case, although rename_if(), rename_at(), and rename_all() have been superseded by rename_with().

head(iris) %>%
  rename_at(vars(starts_with("Petal")), ~ sub("^Petal", "New", .x))
Darren Tsai
  • 32,117
  • 5
  • 21
  • 51