Adding prefix or suffix to most data.frame variable names in piped R workflow

前端 未结 6 1717
一个人的身影
一个人的身影 2020-12-03 05:07

I want to add a suffix or prefix to most variable names in a data.frame, typically after they\'ve all been transformed in some way and before performing a join. I don\'t ha

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-03 06:03

    While Sam Firkes solution using setNames() ist certainly the only solution keeping an unbroken pipe, it will not work with the tbl objects from dplyr, since the column names are not accessible by methods from the usual base R naming functions. Here is a function that you can use within a pipe with tbl objects as well, thanks to this solution by hrbrmstr. It adds predefined prefixes and suffixes at the specified column indices. Default is all columns.

    tbl.renamer <- function(tbl,prefix="x",suffix=NULL,index=seq_along(tbl_vars(tbl))){
      newnames <- tbl_vars(tbl) # Get old variable names
      names(newnames) <- newnames
      names(newnames)[index] <- paste0(prefix,".",newnames,suffix)[index] # create a named vector for .dots
      rename_(tbl,.dots=newnames) # rename the variables
    }
    

    Example usage (Assume auth_users beeing an tbl_sql object):

    auth_user %>% tbl_vars
    tbl.renamer(auth_user) %>% tbl_vars
    auth_user %>% tbl.renamer %>% tbl_vars
    auth_user %>% tbl.renamer(index = c(1,5)) %>% tbl_vars
    

提交回复
热议问题