Sort in R based on criteria

1

I would like to learn how to order a dataframe (List_Habitat) depending on your own criteria.

 List_habitat:
   Specie          Habitat
   Amaranthus      Crop
   Apiaceae        Edge
   Asteraceae      Quercus
   Malvaceae       Wasteland

I want to sort the species based on the habitats that the Quercus habitat appears before the Wasteland, this before the Edge and finally the Crop habitat.

    
asked by Adrián P.L. 10.11.2017 в 15:57
source

1 answer

1

Adrián:

The key is to convert the "Habitat" column into a factor ordered according to the criteria you prefer. It would be something like that, following your ordination criteria:

# Dataframe    
List_habitat<-data.frame(Specie=c("Amaranthus", "Apiaceae", "Asteraceae", "Malvaceae"), Habitat=c("Crop", "Edge", "Quercus", "Wasteland"))

# Conversión a factor ordenado según criterio
List_habitat$Habitat<-factor(List_habitat$Habitat, c("Quercus","Wasteland","Edge","Crop"),ordered = TRUE)

# Ordenar dataframe
List_habitat<-List_habitat[order(List_habitat$Habitat),]

List_habitat


Specie   Habitat
3 Asteraceae   Quercus
4  Malvaceae Wasteland
2   Apiaceae      Edge
1 Amaranthus      Crop

Greetings

    
answered by 11.11.2017 / 18:56
source