Reut Zabag
Reut Zabag

Reputation: 31

Rename several columns using start with in r

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!

Upvotes: 2

Views: 1018

Answers (1)

Darren Tsai
Darren Tsai

Reputation: 35584

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))

Upvotes: 2

Related Questions