I have the following dataframe:
library(dplyr)
df <- data.frame(gh225 = "foo1", gh765 = "foo2", gauskper = "foo3") %>%
rename_all(funs(stringr::str_replace_all(., "gh", "v")))
I want to use rename_all combined with if_else but I can't find the way, the logic would be something like this (but with variables):
if_else(stringr::str_detect(columns, "au"), "id_per", columns)
Put into words, I want to change the name gauskper to id_per.
We may use rename_with as rename_all is deprecated
library(dplyr)
library(stringr)
data.frame(gh225 = "foo1", gh765 = "foo2", gauskper = "foo3") %>%
rename_with(~ str_replace(., "au", "idper"), contains("au"))
Regarding the use of if_else, it just needs a lambda expression i.e. ~
data.frame(gh225 = "foo1", gh765 = "foo2", gauskper = "foo3") %>%
rename_with(~ if_else(str_detect(., "au"), "id_per", .), everything())
gh225 gh765 id_per
1 foo1 foo2 foo3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With