Subsetting with multiple conditions in R

[This article was first published on Data Science Tutorials, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

The post Subsetting with multiple conditions in R appeared first on
Data Science Tutorials –

Subsetting with multiple conditions in R, The filter() method in the dplyr package can be used to filter with many conditions in R.

With an example, let’s look at how to apply a filter with several conditions in R.

Let’s start by making the data frame.

df<-data.frame(Code = c('A','B', 'C','D','E','F','G'),
                 Score1=c(44,46,62,69,85,77,68),
                score2=c(35,78,45,89,67,49,70),
                 score3=c(57,62,55,88,43,90,57))
df

As a result, the final data frame will be

Code score1 score2 score3
1    A     44     35     57
2    B     46     78     62
3    C     62     45     55
4    D     69     89     88
5    E     85     67     43
6    F     77     49     90
7    G     68     70     57

Online Course R Statistics: Statistics with R »

Subsetting with multiple conditions in R

Using the or condition to filter two columns.

Let’s load dpyr package first,

library(dplyr)
result <- df%>% filter(score>50 | score2>55)
result

as a result, the filtered data frame

   Code score1 score2 Score3
1    B     46     78     62
2    C     62     45     55
3    D     69     89     88
4    E     85     67     43
5    F     77     49     90
6    G     68     70     57

Filtering with multiple conditions in R:

Using and condition to filter two columns.

library(dplyr)
df2 <- df %>% filter(score1>45 & score2>45)
df2

so the filtered data frame is

   Code score1 score2 Score3
1    B     46     78     62
2    D     69     89     88
3    E     85     67     43
4    F     77     49     90
5    G     68     70     57

Best Books to Learn R Programming – Data Science Tutorials

Learning Tips!

The post Subsetting with multiple conditions in R appeared first on Data Science Tutorials

To leave a comment for the author, please follow the link and comment on their blog: Data Science Tutorials.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)