4

I have a large dataset that I am trying to filter based on the value of 2 separate columns. For each row I have a column showing their total count (tot) and a column showing the total times that type of sample was seen (tot.type).

I want to filter my data based on both (tot) and (tot.type) where (tot) OR (tot.type) must be greater than or equal to 2, for example.

All examples I have found for filtering based on multiple values use "AND" but nothing where you use "OR"...

Example data:
name = c("A","B","C","D","E")
rx = c(1,0,2,1,1)
ry = c(0,1,1,0,0)
rz = c(0,0,2,2,3)
type = c("p","q","r","p","r")
tot = c(1,1,5,3,4)
tot.type = c(2,1,2,2,2)
test = data.frame(name,rx,ry,rz,tot,tot.type)

In this example I would discard row B, and keep the rest.

I have filtered the data into 2 separate data sets based on just one column or the other, and then merged them but can this be done in one line that generates one data set, rather than doing two separate ones and combining them later?

0

3 Answers 3

5

subset is designed exactly for this:

subset(test, tot.type >= 2 | tot >= 2)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this works perfectly. So simple yet so difficult to find the answer on my own.
By the way, this 'or' condition has an alternative formulation: subset(test,pmax(tot,tot.type)>=2) Generally, thinking about the math may help simplify calculations.
3

Try

test[test$tot>=2 | test$tot.type>=2,]

(p.s. I think there's an error in your example, do you want

test = data.frame(name,rx,ry,rz,type,tot,tot.type) 

instead of

test = data.frame(name,rx,ry,rz,tax,tot,N.tax)

?

Comments

1

You could use rowSums. ("test" is based on @CactusWoman's data)

  test[!!rowSums(test[c('tot', 'tot.type')]>=2),])

Or another option

  test[unique(which(test[c("tot","tot.type")] >= 2,
                           arr.ind = TRUE)[, 1]), ]

1 Comment

Am I missing some inside joke here? Also, @DavidArenburg, you should get a badge for fastest edit ever. It felt like you edited that almost before I hit submit!

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.