Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename columns using `starts_with()` where new prefix is a string

Tags:

r

rename

dplyr

In R, I want to rename all the columns that starts with some prefix (say "oldprefix1", "oldprefix2", "oldprefix3", ... to "newprefix1", "newprefix2", "newprefix3", ...) inside a function. The following code works:

change = function(df) {
    select(df, newprefix = starts_with('oldprefix') )
}
change(test)

But, I would like to pass a string with the new prefix as parameter to the function:

change2 = function(df, prefix) {
    dots = paste0(prefix," = starts_with('oldprefix')"
    select_(df, dots)
}
change2(test, "newprefix")

I have tried using select_() and .dots, but I cannot get it to work together with the starts_with() function. I get the error Error in eval(expr, envir, enclos) : could not find function "starts_with".

like image 581
bonna Avatar asked Oct 05 '17 12:10

bonna


People also ask

How do I rename a column in R using dplyr?

To rename a column in R you can use the rename() function from dplyr. For example, if you want to rename the column “A” to “B”, again, you can run the following code: rename(dataframe, B = A) .

How do I rename multiple columns?

To change multiple column names by name and by index use rename() function of the dplyr package and to rename by just name use setnames() from data. table . From R base functionality, we have colnames() and names() functions that can be used to rename a data frame column by a single index or name.


1 Answers

The option would be to use rename_at

mtcars %>% 
    rename_at(vars(starts_with('m')), funs(paste0('prefix', .)))

For changing an old name, use sub

change2 <- function(df, oldpref, newpref) {
  df %>%
       rename_at(vars(starts_with(oldpref)), funs(sub(oldpref, newpref, .)))


 }

change2(mtcars, "m", "newprefix") %>%
       names
#[1] "newprefixpg" "cyl"         "disp"        "hp"          "drat" 
#[6]   "wt"          "qsec"        "vs"          "am"          "gear" 
#[11] "carb"    
like image 182
akrun Avatar answered Nov 14 '22 22:11

akrun