R dplyr: rename variables using string functions

后端 未结 8 587
说谎
说谎 2020-11-28 03:45

(Somewhat related question: Enter new column names as string in dplyr's rename function)

In the middle of a dplyr chain (%>%), I wou

8条回答
  •  猫巷女王i
    2020-11-28 04:30

    Both select() and select_all() can be used to rename columns.

    If you wanted to rename only specific columns you can use select:

    iris %>% 
      select(sepal_length = Sepal.Length, sepal_width = Sepal.Width, everything()) %>% 
      head(2)
    
      sepal_length sepal_width Petal.Length Petal.Width Species
    1          5.1         3.5          1.4         0.2  setosa
    2          4.9         3.0          1.4         0.2  setosa
    

    rename does the same thing, just without having to include everything():

    iris %>% 
      rename(sepal_length = Sepal.Length, sepal_width = Sepal.Width) %>% 
      head(2)
    
      sepal_length sepal_width Petal.Length Petal.Width Species
    1          5.1         3.5          1.4         0.2  setosa
    2          4.9         3.0          1.4         0.2  setosa
    

    select_all() works on all columns and can take a function as an argument:

    iris %>% 
      select_all(tolower)
    
    iris %>% 
      select_all(~gsub("\\.", "_", .)) 
    

    or combining the two:

    iris %>% 
      select_all(~gsub("\\.", "_", tolower(.))) %>% 
      head(2)
    
      sepal_length sepal_width petal_length petal_width species
    1          5.1         3.5          1.4         0.2  setosa
    2          4.9         3.0          1.4         0.2  setosa
    

提交回复
热议问题