Home > database >  How to rename suffix in column
How to rename suffix in column

Time:04-19

I would like to replace 2003 with x, 2004 with y, and 2005 with z, in the column suffixes. For example, I would like to transform:

enter image description here

In:

enter image description here

Here's the reproducible example:

structure(list(id = c(1, 1, 1, 1, 1), xd_2004 = c(1, 1, 1, 1,
1), xd_2003 = c(1, 1, 1, 1, 1), xe_2004 = c(1, 1, 1, 1, 1), xe_2003 = c(1,
1, 1, 1, 1), xd_2005 = c(1, 1, 1, 1, 1), xe_2005 = c(1, 1, 1,
1, 1)), class = "data.frame", row.names = c(NA, -5L))

CodePudding user response:

Using rename_with we could do:

library(dplyr)
library(stringr)

df %>% 
  rename_with(., ~str_replace_all(., '2004', "y")) %>% 
  rename_with(., ~str_replace_all(., '2003', "x")) %>% 
  rename_with(., ~str_replace_all(., '2005', "z")) 
id xd_y xd_x xe_y xe_x xd_z xe_z
1  1    1    1    1    1    1    1
2  1    1    1    1    1    1    1
3  1    1    1    1    1    1    1
4  1    1    1    1    1    1    1
5  1    1    1    1    1    1    1
  • Related