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 reproducible example if that will help:
library(dplyr)
if(this_team != "") {
newdf <- mydf %>%
filter(team == this_team) %>%
mutate(totalrows = nrow(.)) %>%
group_by(x1, y1) %>%
summarize(dosomestuff)
} else {
newdf <- mydf %>%
filter(firstname == this_name & lastname == that_name) %>%
mutate(totalrows = nrow(.)) %>%
group_by(x1, y1) %>%
summarize(dosomestuff)
}
I am creating a function in R that does some data manipulations on the mydf dataframe. If I pass a value to the function's team_name parameter, then I would like to filter the dataframe using the 'team' column. If I don't pass a value to the team_name parameter, then it defaults to "", and I instead pass values for this_name and that_name, which correspond to the columns 'firstname' and 'lastname' in mydf.
Is there a better way to do this, rather than having to create the entire dplyr pipeline again in two separate if else statements? My actual pipeline of code is much longer than 4 lines each, so having to reproduce code like this is quite frustrating.