kray
kray

Reputation: 377

R tibble rename columns with regular expressions

I have multiple duplicated columns in a table after several dplyr::joins. A simple version of the table looks like this:

col1 col2 col3 col4.x col4.y col5.x col5.y

I want to get to rename to:

col1 col2 col3 col4 col5

I was able to remove the *.y columns with select(tablename, -matches("*.y"))

Resulting in:

col1 col2 col3 col4.x col5.x

From here, I am thinking the rename_if() should work, but I am at a loss as to how to get col4.x and col5.x renamed to col4 and col5.

Any advice would be appreciated.

Upvotes: 2

Views: 1813

Answers (1)

Gabi
Gabi

Reputation: 1343

mytibble %>% rename_all(gsub, pattern = '\\.x', replacement = '')

Upvotes: 4

Related Questions