有条件地从数据框中删除行

时间:2017-08-17 19:22:02

标签: r data.table

我需要有条件地从R中的data.table中删除行。 我需要从1:4, 9:12,17:20...中删除行,直到data.table中的data.table行数(56),称为" dfx"。

我有以下代码,但它不能完成我想要的工作。有人可以帮我纠正这个吗?

for (ij in seq(from = 1, to = dim(dfx)[1], by = 8)) {
    dfx <- dfx[-(ij:4),]
}

1 个答案:

答案 0 :(得分:0)

这应该这样做。

#Making a reproducible example with 56 rows
V1 <- c(1:56)
V2 <- c(56:1)
dfx <- data.frame(V1, V2)

#Defining Rows to Drop
Drop1 <- c(1:4)
Drop2 <- c(9:12)
Drop3 <- c(17:20)
Drops <- c(Drop1,Drop2,Drop3)
Drops <- as.vector(Drops)

#Removing Rows
dfx2 <- dfx[ !(row.names(dfx) %in% Drops) , ]