如何重命名列中的后缀

How to rename suffix in column

我想在列后缀中用 x 替换 2003,用 y 替换 2004,用 z 替换 2005。 例如,我想转换:

在:

这是可重现的例子:

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

使用rename_with我们可以做到:

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

我们也可以在 str_replace_all

中使用命名向量
library(dplyr)
library(stringr)
df %>% 
  rename_with(~ str_replace_all(.x, setNames(c('x', 'y', 'z'), 2003:2005)))

-输出

  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