Nikolay Nenov
Nikolay Nenov

Reputation: 587

Conditional subsetting in R based on a value in another data frame

I want to subset a data frame based on a value in another data frame (that's the easy part). On top of that, I wish to tell R that if the value in the second df is above certain level, then the subset should consist of all the values in the first df. That's a mouthful, so here's an example:

DF1 looks like this:

|   date    |  value |
----------------------
| Jul 1     |  1     |
| Jul 2     |  2     |
| Jul 3     |  3     |
| Jul 4     |  4     |

For simplicity let's say DF2 looks like this

value=99
df2<-data.frame(value)

Again, I want to tell R that if the value in df2 is above 5, then the subset of df1 should contain values 1,2,3,4.

Here's what I'm trying that does not work:

subset(df1, value %in% ifelse(df2$value[1]>5, c(1,2,3,4), df2$value[1]))

Can you help, please? Also, additional points if you could explain why is the above code not working.

Cheers!

Upvotes: 0

Views: 593

Answers (2)

arvi1000
arvi1000

Reputation: 9582

How about plain old if() rather than ifelse().

For example:

if(F) c(1:4) else 99 # returns 99
if(T) c(1:4) else 99 # returns vector c(1:4)

Upvotes: 2

Nikolay Nenov
Nikolay Nenov

Reputation: 587

For me

subset(df1, value %in% (if (df2$value[1]>99)  c(0,1,2,3) else (df2$value[1])))

did the magic.

Upvotes: 2

Related Questions