How to delete row n and n+1 in a dataframe?
I have several dataframes in which I want to delete each row that matches a certain string. I used the following code to do it:
df[!(regexpr("abc", df$V4) ==1),]
How can I delete the row that is following, e.g. if I delete row n as specified by the code above, how can I additionally delete row n+1?
My first try was to simply find out the indices of the desired rows, but that won't work, as I need to delete rows in different dataframes which are of different lengths. So the indices vary.
Use which() on your logical expression and then you can just add 1 to the result.
sel <- which(grep("abc", df$V4)) sel <- c(sel, sel+1) df[-sel,]
I would suggest taking out and manipulating the logical vector directly. Suppose we have the vector:
x = c(5,0,1, 4, 3)
and we want to do:
x[x > 3]
First, note that:
R> (s_n = x>3)  TRUE FALSE FALSE TRUE FALSE
R> (s_n1 = as.logical(s_n + c(F, l[1:(length(s_n)-1)])))  TRUE TRUE FALSE TRUE TRUE
gives you what you want.
In your particular example, something like:
s_n = !(regexpr("abc", df$V4) == 1) s_n1 = as.logical(s_n + c(F, l[1:(length(s_n)-1)]))) df[s_n1, ]
df[which(!(regexpr("abc", df$V4) ==1))+c(0,1),]