Is there anyway to apply a conditional group_by? For example (code DOESN'T work btw but its just to show the iris dataset so you get the gist):
iris$Sepal.Width.r <- round(iris$Sepal.Width)
for(i in 1:2){
test <- iris %>%
ifelse(i == 1, group_by(Species), group_by(Sepal.Width.r)) %>% #****
summarise(avgLWdiff = (mean(Petal.Length) - mean(Petal.Width)))
print(test)
}
The starred line #**** is my very rough (and wrong) guess on what it should look like. I think the questions I've seen from others so far ask about the if statement within the summarise/mutate line but I haven't seen anyone ask about the group_by line. Also, the contents within my summarise takes up a few lines.
My desired output is:
when i==1:
Species avgLWdiff
<fct> <dbl>
1 setosa 1.22
2 versicolor 2.93
3 virginica 3.53
when i == 2:
Sepal.Width.r avgLWdiff
<dbl> <dbl>
1 2 2.76
2 3 2.76
3 4 1.54