满足条件时删除行并跟随208行

时间:2017-10-26 00:55:46

标签: r dataframe

我有data.frame 176800次观察。 我想在满足以下条件时删除行:

full_data_string_split$split1=="SP#" & full_data_string_split$split2=="11"

我知道这个条件在425个案例中已满,当我执行以下操作时会删除425行:

full_data_string_split_removed1 <- full_data_string_split[!(full_data_string_split$split1 == "SP#" & full_data_string_split$split2 ==  "11"), ]

我现在的问题是:如何删除具有给定条件的行和以下207行以将data.frame减少到88400个观察值?

2 个答案:

答案 0 :(得分:2)

使用reproducible example解决这个问题要容易得多,但我相信这应该可行:

indicies_with_match <- which(full_data_string_split$split1 == "SP#" & full_data_string_split$split2=="11")
indicies_to_remove <- indicies_with_match + rep(0:207, each = length(indicies_with_match))

results <- full_data_string_split[-indicies_to_remove, ]

请务必查看?which,然后考虑x <- c(1, 5, 9)以及执行x + rep(0:2, each = length(x))时会发生什么

答案 1 :(得分:1)

也许这会有用吗?

result <- which(airquality$Month == 5 & airquality$Temp == 67)
keepalso <- 3
keep <- Reduce("c", apply(cbind(result, result+keepalso), 1, function(x) c(x[1]:x[2])))
airquality[keep,]

   # Ozone Solar.R Wind Temp Month Day
# 1     41     190  7.4   67     5   1
# 2     36     118  8.0   72     5   2
# 3     12     149 12.6   74     5   3
# 4     18     313 11.5   62     5   4
# 28    23      13 12.0   67     5  28
# 29    45     252 14.9   81     5  29
# 30   115     223  5.7   79     5  30
# 31    37     279  7.4   76     5  31

适应您的情况

result <- which(full_data_string_split$split1=="SP#" & full_data_string_split$split2=="11")
discardalso <- 207
discard <- Reduce("c", apply(cbind(result, result+discardalso), 1, function(x) c(x[1]:x[2])))
full_data_string_split[-discard,]