Replacement for “rename” in dplyr

前端 未结 6 902
长情又很酷
长情又很酷 2020-12-02 05:51

I like plyr\'s renaming function rename. I have recently started using dplyr, and was wondering if there is an easy way to rename variables using a function fr

6条回答
  •  执笔经年
    2020-12-02 06:21

    You can actually use plyr's rename function as part of dplyr chains. I think every function that a) takes a data.frame as the first argument and b) returns a data.frame works for chaining. Here is an example:

    library('plyr')
    library('dplyr')
    
    DF = data.frame(var=1:5)
    
    DF %>%
        # `rename` from `plyr`
        rename(c('var'='x')) %>%
        # `mutate` from `dplyr` (note order in which libraries are loaded)
        mutate(x.sq=x^2)
    
    #   x x.sq
    # 1 1    1
    # 2 2    4
    # 3 3    9
    # 4 4   16
    # 5 5   25
    

    UPDATE: The current version of dplyr supports renaming directly as part of the select function (see Romain Francois post above). The general statement about using non-dplyr functions as part of dplyr chains is still valid though and rename is an interesting example.

提交回复
热议问题