首页 > 解决方案 > 如何在满足条件的所有行之前只选择前 10 行?

问题描述

我在 R 环境中有一个时间序列数据集。变量 CB_Day 在某些日期等于 MPD,在大多数日期等于 0。

我想删除除 MPD 天和前 10 天之外的所有行。

我尝试过subsethead()tail(),但它们没有用。

有人能告诉我根据我在 R 中的条件删除记录的正确命令是什么吗?

结果应该是包含所有其他列的整个表。只有行需要被删除。

标签: rsubset

解决方案


如果我做对了,那么这样的事情应该会有所帮助......

# create data where CB_Day is always 0 (please provide reproducible data next time)
df <- data.frame(MPD  = 1:100, CB_Day = rep(0, 100))
# sometimes CB_Day is same as MPD
df$CB_Day[c(20, 70)] <- df$MPD[c(20, 70)]
# Find where both are same
same <- which(df$MPD== df$CB_Day)
# create vectors with "10 rows before CB_Day and MPD are same" to the row where they are same
keep <- sapply(same, function(x){(x-10):x})
# make it a vector instead of a matrix
keep <- unlist(keep)
# select the rows
df[keep, ]

推荐阅读