dplyr::rename_all & dplyr::if_else

Viewed 98

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.

3 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

You can combine the conditions in a single function

df %>% 
  rename_all(
    .funs = function(x){
      x %>% 
        stringr::str_replace_all(., "gh", "v") %>% 
        stringr::str_replace_all(., "gauskper", "id_per")
    }
)

The question is already answered by akrun and is best, but when I understand you correctly:

"Put into words, I want to change the name gauskper to id_per."

then

Best way to achieve this is:

library(dplyr)
df %>% 
  rename(id_per = gauskper)
  gh225 gh765 id_per
1  foo1  foo2   foo3
Related