Erich Neuwirth
Erich Neuwirth

Reputation: 1041

renaming a bunch of variables in dplyr

After a left_join I have variables var1.x var2.x ... and var1.y var2.y . I would like to rename them to var1_tot var2_tot and var1_part var2_part. I can do this but combining names and string replacement functions. Can this be done as part pf a dplyr chain by using dplyr's rename function and ends_with?

Upvotes: 1

Views: 2493

Answers (3)

Aman Basu
Aman Basu

Reputation: 1

The following should work.

rename_at(mydf,vars(matches(".x")),function(x) str_replace(x,".x","_total"))

Upvotes: 0

Erich Neuwirth
Erich Neuwirth

Reputation: 1041

In fact

mydf %>% rename_at(vars(ends_with(".x")),funs(str_replace(.,".x","_total")))

did work

Upvotes: -1

www
www

Reputation: 39174

Like this? dt is an example data frame. dt2 is the final output.

library(dplyr)

dt <- data_frame(var1.x = 1:3, var2.x = 4:6, var1.y = 7:9, var2.y = 10:12)

dt2 <- dt %>%
  rename_at(vars(ends_with(".x")), funs(sub(".x", "_tot", .))) %>%
  rename_at(vars(ends_with(".y")), funs(sub(".y", "_part", .)))
dt2
# A tibble: 3 x 4
  var1_tot var2_tot var1_part var2_part
     <int>    <int>     <int>     <int>
1        1        4         7        10
2        2        5         8        11
3        3        6         9        12

Upvotes: 6

Related Questions