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

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

    I'm a little late to the party on this, but after staring at the programming vignette for a long time, I found the relevant example in the Different input and output variable .

    In my simpler use case, I just needed to rename a column to the value of a string:

    > df1 = data_frame(index = 1:5, value = c(10, 20, 30, 40, 50))
    > df1
    # A tibble: 5 x 2
      index value
       
    1     1    10
    2     2    20
    3     3    30
    4     4    40
    5     5    50
    
    > newname = 'blau'
    > newname2 = 'wheee'
    
    > df1 %>% rename(!!newname := value, !!newname2 := index)
    # A tibble: 5 x 2
      wheee  blau
       
    1     1    10
    2     2    20
    3     3    30
    4     4    40
    5     5    50
    

    So if you're happy to do that manually, you can just:

    df %>%
      rename(!!paste("Sepal.Length", "xxx", sep = ".") := Sepal.Length)
    

    If, however, you need something that automatically appends ".xxx" to whatever column name is supplied to it, I recommend you have a close look at that section. It's still a bit over my head, unfortunately, but I can see that it's doable >_>

提交回复
热议问题