'Aggregate function does not respect alphabetical order of a vector

I have a data.frame that (simplified) looks like this:

Binomial<-c(rep("Capra aegagrus",2),rep("Capreolus capreolus",3),"Capra ibex")
area<-c(500,200,10,300,15,5)
mydata<-data.frame(Binomial,area)

I want to obtain a new data.frame with the names of the species (mydata$Binomial) and the sum of all the areas of each species. This is my process so far:

#sum all the areas of each species 
a<-aggregate(mydata$area,list(mydata$Binomial),FUN=sum)
#create a vector with a length equal to mydata number of rows
n<-max(lengths(mydata)) 
#insert the total of the areas of each species in the first row, and fill the rest with NA 
b<-lapply(a, `length<-`, n) 
summary(b)  
#Group.1 is the species, x is the area
#create a column with the species 
mydata$Binomial_2<-b$Group.1 
#create a column with the areas
mydata$area_tot<-b$x 
#create a final data frame with the species and the total of the areas 
mydata_2<-mydata[c(1:3),c(3:4)]

So far it worked on different datasets. The problem is that if I check a, I see that species are not in the same order as they were in mydata: now Capra ibex is before Capreolus capreolus. This messes up my following analyses. Do you have a suggestion on how to preserve the alphabetical order of mydata in this script? This means it should be Capra aegagrus, then Capreolus capreolus, and lastly Capra ibex in mydata_2 as well. Thanks.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source