Home > Back-end >  Deleting rows by using a for loop if statements
Deleting rows by using a for loop if statements

Time:10-06

I've the following dataframe:

caratteri <- c("a", "b", "c", "d")
numeri <- c(1, 1, 2, 2)
dataFrameMio <- data.frame(caratteri, numeri)

How can I delete the rows in which the value of the numeri column is 2 by using a for loop and if statements?

I need to do this because, in the case of a big dataframe, I cannot specify manually which rows to delete. I'm a newbie in R, maybe it's possible to do that also without a loop.

CodePudding user response:

As stated in the comments, you really should not do this via a for loop but you can:

caratteri <- c("a", "b", "c", "d")
numeri <- c(1, 1, 2, 2)
dataFrameMio <- data.frame(caratteri, numeri)

result <- list()
for(line in 1:nrow(dataFrameMio))
  if(dataFrameMio$numeri[line] != 2) 
    result <- rbind(result, dataFrameMio[line,])

print(result)

This ist difficult to read and to find errors in and it will perform poorly with larger datasets. Just use subset! Or square brackets as in

dataFrameMio[dataFrameMio$numeri != 2,]
  • Related