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.

Thanks!

Answers


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)
[1]  TRUE FALSE FALSE  TRUE FALSE

So

R> (s_n1 = as.logical(s_n + c(F, l[1:(length(s_n)-1)])))
[1]  TRUE  TRUE FALSE  TRUE  TRUE

Hence,

x[s_n1]

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

should work.


df[which(!(regexpr("abc", df$V4) ==1))+c(0,1),]

Need Your Help

How do I run a JApplet from itself?

java swing user-interface japplet

Basically I need to do this for school, Ive been through all kinds of posts about this and everyone just says "why'd you wanna do that?" and don't answer. So a lot of people need help on this and y...

Django Page Load slowed based on variable local to view code

python django django-views

I am using Django to display a series of test results. I created a view to show the most recent instance of each test result.