How to rename selected columns using dplyr with new column names as strings

前端 未结 6 1309
被撕碎了的回忆
被撕碎了的回忆 2020-12-29 08:53

I have the following tibble:

library(tidyverse)
df <- structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5), Sepal.Width = c(3.5, 
3, 3.2, 3.1, 3.6), Pet         


        
6条回答
  •  长情又很酷
    2020-12-29 09:26

    If you want to use dplyr's rename function, it would be best to create a named vector / list and call it using the .dots argument in the standard evaluation version:

    cols <- c("Sepal.Length", "Petal.Length")
    to_app <- ".xxx"
    cols <- setNames(cols, paste0(cols, to_app))
    
    df %>% rename_(.dots = cols)
    
    ## A tibble: 5 × 3
    #  Sepal.Length.xxx Sepal.Width Petal.Length.xxx
    #*                               
    #1              5.1         3.5              1.4
    #2              4.9         3.0              1.4
    #3              4.7         3.2              1.3
    #4              4.6         3.1              1.5
    #5              5.0         3.6              1.4
    

    Note however, that this approach is subject to change with the next version 0.6.0 of dplyr (see e.g. http://blog.rstudio.org/2017/04/13/dplyr-0-6-0-coming-soon/ and http://dplyr.tidyverse.org/articles/programming.html).

提交回复
热议问题