I have a problem with a single function in R, which(). I use it in my code to select rows that need to be deleted based on a condition. In my example, I have set the condition to be the occurrence of the letter "a" somewhere in the column "var2".
If there is at least one occurrence, then that row gets deleted and the rest is kept. If there is no occurrence of this condition, it deletes ALL rows instead and gives me an empty dataframe!
This is an example of what i mean:
df <- data.frame(var1 = c(1:9), var2 = c(2:11), stringsAsFactors = F)
df <- df[-which(grepl("a", df$var2)),]
It should return the same df as before, since there is no row that contains "a". Instead, after running this line, i have an empty df.
I have tried using ! instead, but that gives the same result.
df <- df[!which(grepl("a", df$var2)),]
What am i doing wrong here?