r - 如何根据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]”不是索引上面行的正确方法,那么正确的方法是什么?
解决方案
您可以使用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']
推荐阅读
- nginx - How to reverse proxy two times with nginx?
- javascript - What is the meaning of this operator ?. in javascript?
- python - 幻想游戏库存程序中的问题(RuntimeError:迭代期间字典大小更改)
- discord.js - guild.members.forEach 不是一个函数
- java - Spring Boot 使用 save 永远不会在 Postgresql 表中插入一行
- c - 如何在 C 中使用外部函数中初始化向量的大小?
- python - 将 html 表数据发送到烧瓶方法并从数据库中检索信息
- php - 如何为我的项目创建 PSR-4 自动加载器?
- python - 这是使用静态函数的好标准吗?
- c# - 登录时 sql server 和 c# 登录出现问题显示 System.Data.SqlClient.SqlException:'无效的对象名称'0Stock.dbo.Login'。