简体   繁体   中英

Conditionally remove rows from a data frame

I need to conditionally remove rows from a data.table in R. I need to remove rows from 1:4, 9:12,17:20... .upto my data.table length of rows (56) in the data.table called "dfx".

I have the following code but it does not do the job I want. Can somebody help me to correct this?

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

This should do it.

#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) , ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM