【问题标题】:How can I rename functionally in dplyr?如何在 dplyr 中重命名功能?
【发布时间】:2018-02-08 02:15:06
【问题描述】:

我想在函数中使用rename_(或rename?)来重命名小标题中的列。例如,假设我在下面的函数中有rename(as_tibble(iris),petal = Petal.Width)`

rr <- function(toRename, newName, dt) { 
  rename_(dt, .dots = rlang::expr(list(!! newName = toRename)))
          }

我可以将要重命名的数据集以及重命名为字符串的元素传递给我可以调用的位置:

rr('petal', 'Petal.Width', dt = as_tibble(iris))

用于将Petal.Width 重命名为petal

我该怎么做?

【问题讨论】:

    标签: r dplyr lazy-evaluation tidyverse


    【解决方案1】:

    我们可以使用sym:=

    rr <- function(dt, oldName, newName) { 
     rename(dt, !!rlang::sym(newName) := !! rlang::sym(oldName))
          }
    
    rr(dt = as_tibble(iris), oldName = 'Petal.Width', newName = 'petal') %>%
          head(., 2)
    # A tibble: 2 x 5
    #  Sepal.Length Sepal.Width Petal.Length petal Species
    #         <dbl>       <dbl>        <dbl> <dbl> <fctr> 
    #1         5.10        3.50         1.40 0.200 setosa 
    #2         4.90        3.00         1.40 0.200 setosa 
    

    【讨论】:

      【解决方案2】:

      为了使其更具可读性和直观性,我们可以使用 embracing :

      rr <- function(dt, oldName, newName) { 
       rename(dt, rename({{ newName }} := {{ oldName }})
            }
      

      有关使用 dplyr 动词编程的更多信息,请参阅 this vignette

      【讨论】:

        猜你喜欢
        • 2017-02-02
        • 1970-01-01
        • 1970-01-01
        • 2018-01-20
        • 2018-02-27
        • 2014-02-25
        • 2011-03-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多