代码之家  ›  专栏  ›  技术社区  ›  Calum You

dplyr::rename_at gives error“must evaluate to column positions or names”[关闭]

  •  1
  • Calum You  · 技术社区  · 7 年前

    我觉得我遗漏了一些基本的东西,但是我在使用时遇到了麻烦 rename_at 使用自定义重命名功能:

    library(tidyverse)
    

    假设我想交换 Sepal 以及名称以开头的列的度量 萼片 . 我希望这能奏效,但它不能:

    iris %>%
      rename_at(vars(starts_with("Sepal"), funs(str_replace(., "(Sepal)\\.(.*)", "\\2\\.\\1"))))
    #> Warning: 'glue::collapse' is deprecated.
    #> Use 'glue_collapse' instead.
    #> See help("Deprecated") and help("glue-deprecated").
    #> Error: `funs(str_replace(., "(Sepal)\\.(.*)", "\\2\\.\\1"))` must evaluate to column positions or names, not a list
    

    如果我包装函数调用而不使用 funs() :

    sepal_renamer <- function(names){
      str_replace(names, "(Sepal)\\.(.*)", "\\2\\.\\1")
    }
    iris %>%
      rename_at(vars(starts_with("Sepal"), sepal_renamer))
    #> Warning: 'glue::collapse' is deprecated.
    #> Use 'glue_collapse' instead.
    #> See help("Deprecated") and help("glue-deprecated").
    #> Error: `sepal_renamer` must evaluate to column positions or names, not a function
    

    我知道我可以用regex的能力得到想要的结果,但我不明白为什么它能起作用 rename_all (甚至) colnames<-() 但不是 雷那米亚特 . 我想要一个解决方案,即使用ReEX做正确的替换是不可能的(比如尝试把名字映射到新的名字)。

    iris %>% rename_all(funs(str_replace(., "(Sepal)\\.(.*)", "\\2\\.\\1"))) %>% colnames
    #> [1] "Length.Sepal" "Width.Sepal"  "Petal.Length" "Petal.Width" 
    #> [5] "Species"
    
    iris %>% `colnames<-`(str_replace(colnames(.), "(Sepal)\\.(.*)", "\\2\\.\\1")) %>% colnames
    #> [1] "Length.Sepal" "Width.Sepal"  "Petal.Length" "Petal.Width" 
    #> [5] "Species"
    

    有人有什么建议吗?我是否遗漏了一些基本的语法知识?这个错误对我来说并不是什么直观的东西,我更困惑的是因为它适用于 雷纳米耶尔 不管怎样。

    1 回复  |  直到 7 年前
        1
  •  3
  •   sbha    7 年前

    ) vars()

    iris %>%
      rename_at(vars(starts_with("Sepal")), ~str_replace(., "(Sepal)\\.(.*)", "\\2\\.\\1")) %>% 
      head(2)
    
      Length.Sepal Width.Sepal 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
    
    推荐文章