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

前端 未结 6 1292
被撕碎了的回忆
被撕碎了的回忆 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:24

    df %>% setNames(paste0(names(.), to.app))
    
    # A tibble: 5 × 3
      Sepal.Length.xxx Sepal.Width.xxx 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
    

    EDIT:

    Apologies for not reading properly. Here's a solution with data.table package.

    var <- names(df)[c(1,3)]
    df %>% setnames(., var, paste0(var, to.app))
    df
    
    # 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
    

提交回复
热议问题