Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr::rename_all & dplyr::if_else

Tags:

string

r

dplyr

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.

like image 884
Paula Avatar asked Oct 24 '25 04:10

Paula


1 Answers

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
like image 130
akrun Avatar answered Oct 26 '25 18:10

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!