'How to rename suffix in column
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:
In:
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))
Solution 1:[1]
We may also use a named vector in str_replace_all
library(dplyr)
library(stringr)
df %>%
rename_with(~ str_replace_all(.x, setNames(c('x', 'y', 'z'), 2003:2005)))
-output
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
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | akrun |
| Solution 2 | TarJae |


