首页 > 解决方案 > 如何根据R中下面的行过滤行

问题描述

我有看起来像这样的数据:

df <- data.frame(station = c("A", "A", "Bad", "A", "B", "Bad", "B", "C"),
  values = c(8.1, 3.3, NA, 9.1, 9.4, 6.5, 15.3, 7.8))

    station values
1       A    8.1
2       A    3.3
3     Bad     NA
4       A    9.1
5       B    9.4
6     Bad    6.5
7       B   15.3
8       C    7.8

我想删除站为“坏”的行上方的行。我最终还将删除电台为“坏”的行,但我知道该怎么做,这是一个单独的问题。

现在的输出应该是这样的:

output <- data.frame(station = c("A", "Bad", "A", "Bad", "B", "C"),
                 values = c(8.1, NA, 9.1, 6.5, 15.3, 7.8))

   station values
1       A    8.1
2     Bad     NA
3       A    9.1
4     Bad    6.5
5       B   15.3
6       C    7.8

到目前为止,我一直在尝试使用 dplyr 过滤器功能,其变化类似于:

output <- df %>% 
  filter(values != ([-1] == "Bad"))

我知道“[-1]”不是索引上面行的正确方法,那么正确的方法是什么?

标签: rdataframefilterdplyr

解决方案


您可以使用lead

library(dplyr)

df %>% filter(lead(station, default = last(station)) != 'Bad')

#  station values
#1       A    8.1
#2     Bad     NA
#3       A    9.1
#4     Bad    6.5
#5       B   15.3
#6       C    7.8

或在基数 R 和 中data.table

#Base R
subset(df, c(tail(station, -1) != 'Bad', TRUE))

#Data table
library(data.table)
setDT(df)[shift(station, fill = last(station), type = 'lead') != 'Bad']

推荐阅读