【问题标题】:Filter dataframe based on different conditions for each group根据每个组的不同条件过滤数据框
【发布时间】:2018-04-03 11:43:32
【问题描述】:
df <- data.frame(loc.id = rep(1:10, each = 10), 
       MG = rep(1:10,times = 10),
       x = runif(100))

如果我想根据多个条件过滤数据,我可以这样做:

df %>% filter(MG > 5 & loc.id < 4)

但是,我有一个过滤条件不同的情况。例如

如果loc.id小于4,则只保留MG 1-4

如果loc.id在5到6之间,只保留MG 5-8

如果loc.id大于6,只保持MG大于8。

【问题讨论】:

  • 一种选择是枚举组合和左连接:使用 data.table mDT = rbindlist(list(CJ(loc.id = 1:3, MG = 1:4), CJ(5:6, 5:8), CJ(7:10, 9:10))); setDT(df)[mDT, on=names(mDT), nomatch=0] 或类似使用 dplyr。

标签: r filter dplyr


【解决方案1】:

为什么不这样:

df %&gt;% filter( (loc.id&lt;4 &amp; between(MG, 1,4)) | (between(loc.id, 5, 6) &amp; between(MG, 5, 8)) | (loc.id&gt;6 &amp; MG&gt;8))

【讨论】:

    【解决方案2】:

    当我需要过滤数据框时,我更喜欢使用以下函数:

    dfalt &lt;- df[which(df$MG &gt; 5 &amp; df$loc.id &lt; 4), ]

    这对我很有用!

    【讨论】:

    • 谢谢,但这对我不起作用。它只过滤所有 MG > 5 和 loc.id 的数据框
    猜你喜欢
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 2012-12-21
    • 2022-01-23
    相关资源
    最近更新 更多