Reputation: 561
How can I use a filter with multiple conditions in conjunction with the pipe %>% operator in R? For Eg:
x <- rep(c(2011:2012),4)
y <- sort(rep(c(1:4),2))
qtr <- as.data.frame(cbind(x,y))
names(qtr) <- c("year","qtr")
Now, I need to filter records for the 3rd quarter of 2012 and I need to use the use the pipe operator in the below step.
z <- dplyr::filter(qtr,qtr$year==2012 & qtr$qtr==3)
Upvotes: 1
Views: 3312
Reputation: 4194
with your example
x <- rep(c(2011:2012),4)
y <- sort(rep(c(1:4),2))
qtr <- as.data.frame(cbind(x,y))
names(qtr) <- c("year","qtr")
you can do:
dplyr::filter(qtr,year==2012 & qtr==3)
#> year qtr
#> 1 2012 3
dplyr::filter(qtr, year==2012, qtr==3)
#> year qtr
#> 1 2012 3
piping:
qtr %>%
filter(year == 2012, qtr == 3)
#> year qtr
#> 1 2012 3
or step-wise
qtr %>%
filter(year == 2012) %>%
filter(qtr == 3)
#> year qtr
#> 1 2012 3
Upvotes: 4