Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter by multiple conditions

Tags:

r

dplyr

I've got data.frame like below

ID  country age
1   X   83
2   X   15
3   Y   2
4   Y   12
5   X   2
6   Y   2
7   Y   18
8   X   85

I need to filter rows for age below 10 and at the same time above 80. How can I do it in the simplest way? For one condition I can use filter(data.frame, age > 80) but I don't know how to do it for two conditions at the same time?

like image 767
anba Avatar asked Jun 26 '18 11:06

anba


People also ask

How do I filter in Excel with multiple conditions?

Type a comma, and then type the condition for the filter, such as C3:C50>3 (To set a condition, first type the address of the "criteria column" such as B1:B, then type an operator symbol such as greater than (>), and then type the criteria, such as the number 3.


3 Answers

I'm not sure from the question if you want the values between 10 and 80 or those below ten and above 80. If you want those between, you can put multiple arguments in filter. If you want those below 10 and above 80 you can use | as an "or" operator:

library(tidyverse)

data %>%
  filter(age > 10,
         age < 80)

data %>%
  filter(age < 10 | age > 80)
like image 159
Ben G Avatar answered Oct 12 '22 22:10

Ben G


Following may help you here too using dplyr

library(dplyr)
##Creating variable dat here which has values in it.
dat <- read.table(text = "ID country age
1   X   83
2   X   15
3   Y   2
4   Y   12
5   X   2
6   Y   2
7   Y   18
8   X   85",
                  header = TRUE)

dat %>%
  filter(age<10 | age>80)
like image 35
RavinderSingh13 Avatar answered Oct 12 '22 23:10

RavinderSingh13


        dat <- read.table(text = "ID country age
                         1   X   83
                         2   X   15
                          3   Y   2
                          4   Y   12
                           5   X   2
                           6   Y   2
                           7   Y   18
                           8   X   85",
                           header = TRUE)

 x<-filter(dat, dat$age>80&dat$age<10) 
 x

Now, you can either use the OR (|) condition or you can use the AND (&) condition based on what you're actually trying to do.

like image 24
Megh Avatar answered Oct 13 '22 00:10

Megh