Having trouble grouping by two variables and having a correct descending order.
I'm using a modified Iris df for this, This is my script:
iris_new <- iris %>%
mutate(number_petals = sample(1:10, size = 150, replace = TRUE))
iris_new %>%
group_by(number_petals, Species) %>%
summarise(n=sum(Petal.Length, na.rm=TRUE)) %>%
arrange(desc(n), by_group = TRUE) %>%
head(25) %>%
ggplot(aes(x=reorder(number_petals,n),y=n,fill=factor(Species))) +
xlab("Number of Petals")+
ylab("Total sum of petal lenghts") +
geom_col() #+ coord_flip()
Two issues with this:
It does not sort by descending ever since I added the second group_by argument (Species).
Head(25) doesn't take the 25 highest sum of petal lengths per number_petals and per species. It takes the 25 highest petal lengths, agnostic of number_petals and Species.
I read that summarise() removes the second group_by variable, but I am not sure what to do with that information.
All help is greatly appreciated!


