代码之家  ›  专栏  ›  技术社区  ›  TarJae

如何在管道中使用rename_with()更改vector中的所有列名

  •  0
  • TarJae  · 技术社区  · 3 年前

    这个问题已经有了很好的答案: Applying dplyr's rename to all columns while using pipe operator How do I add a prefix to several variable names using dplyr?

    我的问题很明确: 重命名_与此等效的是什么:

    newcolnames <- c("one", "two", "three", "four", "five")
    
    head(iris) %>% 
      setNames(newcolnames)
    
    head(iris) %>% 
      `colnames<-`(newcolnames)
    

    head(iris) %>% 
      rename_with(iris, newcolnames)
    

    我想明确地使用 rename_with

    1 回复  |  直到 3 年前
        1
  •  1
  •   MrFlick    3 年前

    看起来不像 rename_with

    iris %>% 
      rename_with(~newcolnames)
    

    作为一种黑客。你也可以使用 rename

    iris %>% 
      rename(!!!setNames(names(.), newcolnames))
    

    setNames 这种方法似乎更合适。