Reputation: 939
I'm trying to do a 'group_by' on a dataframe with a condition inside but something is missing... Yet the solution seems simple..... Any help will be welcome !
var1 <- "no"
result <- starwars %>%
if (var1=="yes") group_by(.,gender)
else if (var1=="no") group_by(.,gender,skin_color)}
Upvotes: 1
Views: 45
Reputation: 9247
This solution might be not the most beautiful one, but it does what you want
if (var1 == "yes")
result <- starwars %>% group_by(gender)
if (var1 == "no")
result <- starwars %>% group_by(gender, skin_color)
and after each group_by
you specify the summary functions you want to apply, or whatever other operation you need
Another possible solution after reading this post is using conditional pipelines, i.e.
starwars %>%
{if (var1 == "yes") group_by(., gender) else .} %>%
{if (var1 == "no") group_by(., gender, skin_color) else .}
Since I don't have a sample data of yours I haven't tested it, but it should work
Upvotes: 2