Search code examples
rdplyrtidyselect

renaming column names with dplyr using tidyselect functions


I am trying to rename a few columns using dplyr::rename and tidyselect helpers to do so using some patterns.

How can I get this to work?

library(tidyverse)

# tidy output from broom (using development version)
(df <- broom::tidy(stats::oneway.test(formula = wt ~ cyl, data = mtcars)))

#> # A tibble: 1 x 5
#>   num.df den.df statistic   p.value method                                      
#>    <dbl>  <dbl>     <dbl>     <dbl> <chr>                                       
#> 1      2   19.0      20.2 0.0000196 One-way analysis of means (not assuming equ~

# renaming
df %>% 
  dplyr::rename(
  .data = .,
  parameter1 = dplyr::matches("^num"),
  parameter2 = dplyr::matches("^denom")
  )
#> Error: Column positions must be scalar

Created on 2020-01-12 by the reprex package (v0.3.0.9001)


Solution

  • Your code works fine with me, however here are some other shorter ways that can help you and you can try;

    library(tidyverse)
    
    # tidy output from broom (using development version)
    (df <- broom::tidy(stats::oneway.test(formula = wt ~ cyl, data = mtcars)))
    
    #> # A tibble: 1 x 5
    #>   num.df den.df statistic   p.value method                                      
    #>    <dbl>  <dbl>     <dbl>     <dbl> <chr>                                       
    #> 1      2   19.0      20.2 0.0000196 One-way analysis of means (not assuming equ~
    
    # renaming
    df %>% 
      rename(parameter1 = matches("^num"),
             parameter2 = matches("^denom"))
    
    # # A tibble: 1 x 5
    # parameter1 parameter2 statistic   p.value method                                               
    # <dbl>      <dbl>     <dbl>     <dbl> <chr>                                                
    #   1          2       19.0      20.2 0.0000196 One-way analysis of means (not assuming..
    
    df %>% 
      rename(parameter1 = contains("num"),
             parameter2 = contains("denom"))
    
    # # A tibble: 1 x 5
    # parameter1 parameter2 statistic   p.value method                                               
    # <dbl>      <dbl>     <dbl>     <dbl> <chr>                                                
    #   1          2       19.0      20.2 0.0000196 One-way analysis of means (not assuming..
    
    df %>% 
      rename(parameter1 = starts_with("num"),
             parameter2 = starts_with("denom"))
    
    # # A tibble: 1 x 5
    # parameter1 parameter2 statistic   p.value method                                               
    # <dbl>      <dbl>     <dbl>     <dbl> <chr>                                                
    #   1          2       19.0      20.2 0.0000196 One-way analysis of means (not assuming..