Accéder au contenu principal

Trier des données dans R

Pour trier une base de données dans R, utilisez la fonction order( ). Par défaut, le tri est ASCENDANT. Faites précéder la variable de tri d'un signe moins pour indiquer l'ordre DESCENDANT. Voici quelques exemples.

Exécutez ce code{:style="position : absolute ; top : 0 ; à droite : 0 ; border-radius : 2px ; background : rgba(3, 239, 98);font-weight : 600 ; text-decoration : none ;" target="_blank"}

# sorting examples using the mtcars dataset
attach(mtcars)

# sort by mpg
newdata <- mtcars[order(mpg),]

# sort by mpg and cyl
newdata <- mtcars[order(mpg, cyl),]

#sort by mpg (ascending) and cyl (descending)
newdata <- mtcars[order(mpg, -cyl),]

detach(mtcars)

Pour vous entraîner, essayez cet exercice de tri avec la fonction order().