过滤/删除不正确的行(加上上下)

时间:2017-03-21 10:53:09

标签: r dplyr

我有一个大型数据集。 我想删除所有不正确的行。另外,我想删除错误行之前和之后的一些行。

我发现了一些有用的东西。但不幸的是,这对我来说并不奏效。 我想我必须使用" rownames"但我无法解决它。 所以我感谢任何有用的建议。

. build/envsetup.sh
lunch 
make liblog V=1 

2 个答案:

答案 0 :(得分:3)

我们获取column等于value的行的索引,并删除索引indxindx + afterindx - before的行。

extract.with.context <- function(df, column, value, before, after) {
    indx <- which(df[[column]] == value)
    df[-c(indx, indx + after, indx - before), ]
}

extract.with.context(dat, "var2", 0, 1, 1)

#   var1 var2 var3
#1     1    1    3
#2     2    1    3
#3     3    1    3
#9     9    1    3
#14   14    1    3
#15   15    1    3
#16   16    1    3
#20   20    1    3

答案 1 :(得分:0)

获得了一些专业帮助:)

toDelete<- c(which(dat$var2==0) , which(dat$var2==0)+1, which(dat$var2==0)-1)
dat <- dat[-toDelete,]

甚至更好(控制没有删除任何内容的情况)

toDelete<- c(which(dat$var2==0) , which(dat$var2==0)+1, which(dat$var2==0)-1)
if (!identical(toDelete,numeric(0))) { dat <- dat[-toDelete,] }