【问题标题】:How does dplyr's select helper function everything() differ from copying?dplyr 的选择辅助函数 Everything() 与复制有何不同?
【发布时间】:2016-09-07 09:37:32
【问题描述】:

有什么用例

select(iris, everything())

相对于例如只是复制data.frame?

【问题讨论】:

    标签: r dataframe dplyr


    【解决方案1】:

    ?select 中寻找对everything 的引用,他们有一个用于重新排序列的示例:

    # Reorder variables: keep the variable "Species" in the front
    select(iris, Species, everything())
    

    在这种情况下,Species 列被移动到第一列,所有列都被保留,没有列重复。

    选择帮助器不仅仅用于 select 函数 - 例如,在 dplyr 1.0 及更高版本中,您可能希望在 across() 中使用它来改变或汇总所有列。

    自从提出这个问题以来,选择助手已被分解到他们自己的包中,tidyselecttidyselect page on CRAN 有很长的反向导入列表 - 很可能许多导入 tidyselect 的包都有 everything() 有用的情况。

    【讨论】:

      【解决方案2】:

      另一个示例用例:

      # Moves the variable Petal.Length to the end
      select(iris, -Petal.Length, everything())
      

      (我在这里看到了:https://stackoverflow.com/a/30472217/4663008

      无论哪种方式,Gregor 的回答和我的回答都让我感到困惑——我希望 Species 在 Gregor 的示例中被复制或在我的示例中被删除。例如如果您根据前两个示例尝试更复杂的操作,则不起作用:

      > dplyr::select(iris, Petal.Width, -Petal.Length, everything())
          Petal.Width Sepal.Length Sepal.Width Petal.Length    Species
      1           0.2          5.1         3.5          1.4     setosa
      2           0.2          4.9         3.0          1.4     setosa
      3           0.2          4.7         3.2          1.3     setosa
      

      更新: 在 github 上的 hadley 快速response 之后,我发现使用everything() 和select() 中第一个位置的负数有一个特殊的行为,它将从所有变量开始select(),然后是所有变量() 将它们再次拉出。非第一位置的负变量不会像预期的那样起作用。

      我同意第一个位置的负变量和everything() select_helper 函数需要在文档中更好地解释

      更新 2:?select 的文档现已更新为“正值选择变量;负值删除变量。如果第一个表达式为负,则 select() 将自动从所有变量开始。”

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-27
        • 2016-05-29
        • 2018-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多