【问题标题】:Filtering in dplyr based on certain conditions根据特定条件在 dplyr 中过滤
【发布时间】:2020-03-11 21:11:40
【问题描述】:

我有一个简单的数据框

name <- c("Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune")
type <- c("Terrestrial planet", "Terrestrial planet", "Terrestrial planet", 
      "Terrestrial planet", "Gas giant", "Gas giant", "Gas giant", "Gas giant")
diameter <- c(0.382, 0.949, 1, 0.532, 11.209, 9.449, 4.007, 3.883)
rotation <- c(58.64, -243.02, 1, 1.03, 0.41, 0.43, -0.72, 0.67)
rings <- c(FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE)

df_space <- data.frame(name, type, diameter, rotation, rings)

如何过滤直径比地球大的行星。

我试过了

df_space %>% filter(diameter > df_space[df_space$name == "Earth"])

但它不起作用。 tidyverse 有什么优雅的解决方案吗?

【问题讨论】:

    标签: r filter dplyr


    【解决方案1】:

    您正在寻找:

    filter(df_space, diameter > diameter[name == 'Earth'])
    

    输出:

         name      type diameter rotation rings
    1 Jupiter Gas giant   11.209     0.41  TRUE
    2  Saturn Gas giant    9.449     0.43  TRUE
    3  Uranus Gas giant    4.007    -0.72  TRUE
    4 Neptune Gas giant    3.883     0.67  TRUE
    

    【讨论】:

      【解决方案2】:

      "Earth"进行子集化后,需要选择列"diameter"

      df_space %>%
        filter(diameter > df_space[ df_space$name == "Earth", "diameter" ])
      

      注意:这个答案只是说明了为什么你的代码不起作用,@arg0naut91 的解决方案更dplyry,应该是正确的答案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-20
        • 1970-01-01
        • 2012-12-08
        • 2018-07-10
        • 2023-03-13
        • 2023-01-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多