0

I want to remove from this df rows where m=f, and where t is within 4 of rows where that happen whatever the specific combination of s and b is.

s<- c(1,1,1,1,1,1,2,1)
b<- c(1,1,1,1,1,1,1,2)
m <- c("o","o","o","o","f","o","o","o")
data <- rnorm(8)
t <- c(1,2,3,4,5,7,8,9)
df<- as.data.frame(cbind(s,b,m,data,t))

So in this example I want to remove the row containing 'f' and the rows which contain t of value up to 4 more than this row (so t of 5 to 9), provided that their value of s and b is the same as the row where 'f' was. So in it should remove row 5 and 6, but not row 7 because s is different from where 'f' was detected and not row 8 because b is different.

Sorry it is quite a dense question, I haven't been able to formulate an attempt at it.

1 Answer 1

1

It is generally regarded good practice not to to use function names for variables, so I re-christen your sample data to myDF. I also assume that you don't really want all your columns to be factors what is what you get using cbind() (check out with str( df ). Lastly, it is probably a good idea to make sure that the random data remain consistent. Hence:

set.seed( 55 )
myDF <- data.frame( s = c( 1, 1, 1, 1, 1, 1, 2, 1 ),
                    b = c( 1, 1, 1, 1, 1, 1, 1, 2 ),
                    m = c( "o", "o", "o", "o", "f", "o", "o", "o" ),
                    data = rnorm( 8 ),
                    t = c( 1, 2, 3, 4, 5, 7, 8, 9 ) )

Here is how I would address your problem - I'm sure there are much better ways but this should at least work:

n <- which( myDF$m == "f" )
m <- which( myDF$t >= myDF$t[n] & myDF$t <= myDF$t[n] + 4 )
p <- which( myDF$s == myDF$s[n] )[m]
o <- which( myDF$b == myDF$b[n] )[p]
o <- o[ !is.na( o ) ]
myDF <- myDF[ -o, ]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.