Skip to content

Instantly share code, notes, and snippets.

@nilforooshan
Created August 28, 2024 04:15
Show Gist options
  • Save nilforooshan/5161ef1848e2e8d9f7c853e22bba0686 to your computer and use it in GitHub Desktop.
Save nilforooshan/5161ef1848e2e8d9f7c853e22bba0686 to your computer and use it in GitHub Desktop.
R: Renaming columns with their name ending with a pattern

Renaming columns with their name ending with a pattern

Merging two data frames sharing columns with the same name, those columns will receive .x and .y suffixes for the first and the second merged data frame. Follow this example to renew those columns.

(test <- data.frame(a = 1:5, b.x = 6:10, b.y = 11:15, c.x = 16:20, c.y = 21:25))
  a b.x b.y c.x c.y
1 1   6  11  16  21
2 2   7  12  17  22
3 3   8  13  18  23
4 4   9  14  19  24
5 5  10  15  20  25
colnames(test)[grepl("\\.x", colnames(test))] <- substr(colnames(test)[grepl("\\.x", colnames(test))], 1, nchar(colnames(test)[grepl("\\.x", colnames(test))])-2)
colnames(test)[grepl("\\.y", colnames(test))] <- paste0(substr(colnames(test)[grepl("\\.y", colnames(test))], 1, nchar(colnames(test)[grepl("\\.y", colnames(test))])-2), ".new")
colnames(test)
[1] "a"     "b"     "b.new" "c"     "c.new"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment