【问题标题】:How to write more than one logical condition inside filter如何在过滤器中写入多个逻辑条件
【发布时间】:2017-04-03 18:05:35
【问题描述】:

这是我的数据集:

set.seed(327)

ID <- seq(1:50)

mou <- sample(c(2000, 2500, 440, 4990, 23000, 450, 3412, 4958, 745, 1000),
  50, replace=TRUE)

calls <- sample(c(50, 51, 12, 60, 90, 16, 89, 59, 33, 23, 50, 555),
  50, replace=TRUE)

rev <- sample(c(100, 345, 758, 44, 58, 334, 888, 205, 940, 298, 754),
  50, replace=TRUE)

dt <- data.frame(mou, calls, rev)

我的动机是找到mou 的平均值,其中调用次数大于 34 且小于 200,rev 大于 100 且小于 400。 我开始使用 dplyr 来解决这个问题,但我不太确定如何在过滤器函数中正确使用所需的表达式。

dt %>% filter(???) %>% summarize(mean_mou=mean(mou))

能否请您指导如何在过滤器中正确设置此表达式。

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    为了完整性:

    如果逻辑是AND,您可以简单地在逗号后添加多个条件:

    df %>%
         filter(calls > 34, calls < 200, rev > 100, rev < 400)
    

    如果逻辑是OR,则必须使用通常的逻辑or 符号:|

    df %>%
      filter(calls > 34 | rev > 100)
    

    将它们链接在一起可以工作,但必须注意所做的事情。 例如:

    df %>%
      filter(calls > 34, calls < 200 | rev > 100, rev < 400)
    

    表示calls &gt; 34 AND (calls &lt; 200 OR rev &gt; 100) AND rev &lt; 400

    【讨论】:

      【解决方案2】:

      您可以将条件放在filter 函数中。在你的例子中你几乎就在那里:-)

      ########
      # Setup
      ########
      set.seed(327) # Setting a seed makes the example reproducible
      
      ID <- seq(1:50)
      mou <-
        sample(c(2000, 2500, 440, 4990, 23000, 450, 3412, 4958, 745, 1000),
               50,
               replace = TRUE)
      calls <-
        sample(c(50, 51, 12, 60, 90, 16, 89, 59, 33, 23, 50, 555), 50, replace = TRUE)
      rev <-
        sample(c(100, 345, 758, 44, 58, 334, 888, 205, 940, 298, 754), 50, replace = TRUE)
      
      dt <- data.frame(mou, calls, rev)
      
      library(tidyverse)
      
      ########
      # Here's the direct answer to your question
      ########
      dt %>%
        filter(calls > 34 & calls < 200) %>% 
        filter(rev > 100 & rev < 400) %>% # Using two filters makes things more readable
        summarise(mean_mou = mean(mou))
      
      # 3349
      

      【讨论】:

        【解决方案3】:
        dt %>% 
          filter(., calls > 40 & calls < 200 & rev > 100 & rev <400)  %>%
          summarise( mean(mou))
        
          mean(mou)
        1  2403.333
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-03-10
          • 1970-01-01
          • 2022-01-10
          相关资源
          最近更新 更多