首页 > 解决方案 > 有条件地保留和删除 R 中的行

问题描述

我正在使用 R。假设我有以下数据:

day_of_the_year = seq(as.Date("2010/1/1"), as.Date("2010/1/31"),by="day")
col_1 = rnorm(31,50,5)
col_2 = rnorm(31,100,5)

my_file = data.frame(day_of_the_year, col_1, col_2)

如果满足一组条件,我正在尝试学习如何保留行和删除行,例如:

library(dplyr)

omit <- c("2010-01-12", "2010-01-16", "2010-01-20", "2010-01-25")

#keep rows if condition is met
final <- filter(my_file, !(day_of_the_year %in% omit | col_1 > 50 | col_2 >100))

#delete rows if condition is met
final <- filter(my_file, (day_of_the_year %in% omit | col_1 > 50 | col_2 >100))

问题:这是在 R 中执行此操作的正确方法吗?还有哪些其他方法可以做到这一点?

谢谢

标签: rdplyrdata-manipulationdelete-row

解决方案


推荐阅读