I have several column names in my dataset (eat10.18) that have the suffix "_10p." I'd like to change that suffix to be "_p_10" but preserve the rest of the variable name. I only want this to affect columns that end in the exact string "_10p." I cannot figure out how to make this work with rename_with(). Can anyone help? Faux data below:
eat10.18 <- data.frame(id = c(1000, 1001, 1002),
eat_10 = c(2, 4, 1),
eat_10p = c(1, 2, 3),
run_10p = c(1, 1, 2))
In the above example, the variables "id" and "eat_10" would remain the same, but "eat_10p" and "run_10p" would become "eat_p_10" and "run_p_10"
Thanks for your help!
CodePudding user response:
library(tidyverse)
eat10.18 %>%
rename_with(~str_replace(.,'_10p$', '_p_10'))
id eat_10 eat_p_10 run_p_10
1 1000 2 1 1
2 1001 4 2 1
3 1002 1 3 2
CodePudding user response:
I suggest using gsub
and referring to this post.
names(eat10.18) <- gsub(x = names(eat10.18), pattern = "_10p", replacement = "_p_10")
Result
id | eat_10 | eat_p_10 | run_p_10 |
---|---|---|---|
1000 | 2 | 1 | 1 |
1001 | 4 | 2 | 1 |
1002 | 1 | 3 | 2 |