【问题标题】:Return number of rows from dplyr filter从 dplyr 过滤器返回行数
【发布时间】:2018-10-08 18:19:19
【问题描述】:

我正在寻找一段简单的代码来报告从过滤器返回的行数。使用iris 数据集,

iris %>%
  filter(Species == 'setosa',
         Sepal.Length >= 5.7) 

此语句返回三行,因此我希望输出在控制台中仅读取“3”。更好的是,我最终想将此对象命名为“Answer1”。

【问题讨论】:

    标签: r filter dplyr


    【解决方案1】:

    tally 函数对满足条件的行进行计数,并返回一个 data.frame,其计数位于 n 列中:

    iris %>% tally(Species == 'setosa' & Sepal.Length >= 5.7)
    
      n
    1 3
    

    如果你只想要数字,我想目前的惯用方式可能是:

    library(purrr)
    iris %>% tally(Species == 'setosa' & Sepal.Length >= 5.7) %>% pluck("n")
    
    [1] 3
    

    或者,如果您喜欢 filter,只需通过管道发送到 nrow:

    iris %>% filter(Species == 'setosa', Sepal.Length >= 5.7) %>% nrow
    
    [1] 3
    

    【讨论】:

    • 旁注:有趣/烦人的是 pluck 没有在 purrr 的文档索引中列出。
    • 超级烦人
    【解决方案2】:
    iris %>%
        filter(Species == 'setosa', Sepal.Length >= 5.7) %>%
        count()
    

    【讨论】:

    • 请花时间向 OP 以及可能遇到此问题的未来访客解释您的回答。
    猜你喜欢
    • 2014-04-19
    • 2019-03-09
    • 2020-03-14
    • 2021-09-04
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 2015-02-23
    • 1970-01-01
    相关资源
    最近更新 更多