1

我正在尝试使用dplyr::rename和 tidyselect 助手重命名一些列,以使用一些模式来做到这一点。

我怎样才能让它工作?

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

reprex 包于 2020-01-12 创建(v0.3.0.9001)

4

2 回答 2

2

你的代码对我来说很好,但是这里有一些其他更短的方法可以帮助你,你可以试试;

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..
于 2020-01-12T11:57:40.703 回答
2

我们也可以rename从一个named向量

library(dplyr)
library(stringr)
df %>% 
     rename(!!!set_names(names(df)[1:2], str_c('parameter', 1:2)))
# 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 equal variances)
于 2020-01-12T17:12:29.737 回答