我有这样的数据:
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“不是对上面的行进行索引的正确方法,那么正确的方法是什么呢?
发布于 2021-05-02 04:15:24
您可以使用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']发布于 2021-05-02 04:23:03
另一个基本的R解决方案是:
df[-(which(df$station == "Bad") - 1),]输出
station values
1 A 8.1
3 Bad NA
4 A 9.1
6 Bad 6.5
7 B 15.3
8 C 7.8发布于 2021-05-02 17:10:57
我们也可以
subset(df, c(station[-1] != "Bad", TRUE))https://stackoverflow.com/questions/67352911
复制相似问题