Let me share an example of what I\'m trying to do, since the title may not be as clear as I\'d like it to be. This doesn\'t have reproducible code, but i can add a reproduci
Building on lukeA's comment, you could also use case_when()
:
library(dplyr)
y <- ""
data.frame(x = 1:5) %>%
filter(case_when(y=="" ~ x > 3, #When y == "", x > 3
T ~ x<3) #Otherwise, x < 3
) %>%
tail(1)
This would be better particularly if you have more than two conditions to evaluate.
See if the below code works, where we insert the if-else
condition in the filter
statement. This makes sense because the latter statements accepts a logical statement as its input -- we just use the former statement to control the value of the input.
library(dplyr)
newdf <- mydf %>%
filter(
if (this_team != "") {
team == this_team
} else {
firstname == this_name & lastname == that_name
}
) %>%
mutate(totalrows = nrow(.)) %>%
group_by(x1, y1) %>%
summarize(dosomestuff)
You could do
library(dplyr)
y <- ""
data.frame(x = 1:5) %>%
{if (y=="") filter(., x>3) else filter(., x<3)} %>%
tail(1)
or
data.frame(x = 1:5) %>%
filter(if (y=="") x>3 else x<3) %>%
tail(1)
or even store your pipe in the veins of
mypipe <- . %>% tail(1) %>% print
data.frame(x = 1:5) %>% mypipe