【问题标题】:How to filter rows based on the previous row and keep previous row using dplyr?如何根据前一行过滤行并使用 dplyr 保留前一行?
【发布时间】:2019-06-18 07:47:43
【问题描述】:

我正在尝试使用基于前一行的条件对数据集的行进行子集化,同时将前一行保留在子集化数据中。这与这里的问题基本相同,但我正在寻找一种 dplyr 方法:

Select specific rows based on previous row value (in the same column)

我已将 cmets 中应用的 dplyr 方法用于该答案,但我无法弄清楚保留前一行的最后一步。

我可以获得支持我感兴趣的条件的行(incorrect,前一行不是enter)。

set.seed(123)
x=c("enter","incorrect","enter","correct","incorrect",
"enter","correct","enter","incorrect")
y=c(runif(9, 5.0, 7.5))
z=data.frame(x,y)

filter(z, x=="incorrect" & lag(x)!="enter")

正如预期的那样:

      x        y
1 incorrect 7.351168 

我想要生成的是这样,以便我根据条件过滤的所有行都存储在原始数据集中它们之前的行:

        x        y
1   correct 7.207544
2 incorrect 7.351168

任何帮助将不胜感激!

【问题讨论】:

  • 你能显示预期的输出吗
  • 显示预期输出会很有帮助。也许z %>% slice(which(x == "incorrect" & lag(x) != "enter") + c(-1, 0))
  • “哪种有效,但它返回包含输入的行,而不是不正确的情况。”我没有看到这个。如果您添加z$id = 1:nrow(z),您会看到id 1 和8 是“输入”并且位于“不正确”之前,而正是这些“输入”行由filter(z,x=="incorrect" & lag(x)!="enter" | x=="enter" & lead(x)=="incorrect") 保留。如果这不是您想要的,请解释原因并显示您想要的输出。
  • @Gregor 道歉,我解决该问题的尝试具有误导性,因此我已更新并添加了预期输出。希望现在更清楚了。

标签: r filter dplyr conditional-statements subset


【解决方案1】:

通过过滤你可以做到:

z %>%
  filter( (x == "incorrect" & lag(x) != "enter") | lead(x == "incorrect" & lag(x) != "enter") )

给予:

          x        y
1   correct 7.207544
2 incorrect 7.351168

【讨论】:

  • 我完全明白,为什么第一个条件(x == "incorrect" & lag(x) != "enter") 括在括号中,而第二个条件lead(x == "incorrect" & lag(x) != "enter") 不是?非常感谢您的回答。
  • 第二个条件和第一个条件一样用括号括起来; lead 部分不会带来任何要评估的新条件,它只是查找括号中的条件为 TRUE 的下一行。
猜你喜欢
  • 2020-12-17
  • 1970-01-01
  • 1970-01-01
  • 2021-11-11
  • 2021-08-01
  • 1970-01-01
  • 2017-06-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多