0
0
R Programmingprogramming~5 mins

Sorting with order() in R Programming - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the order() function do in R?
The order() function returns the indices that would sort a vector or data frame. You can use these indices to rearrange data in ascending or descending order.
Click to reveal answer
beginner
How do you sort a vector ascending using order()?
Use vec[order(vec)]. This returns the vector elements sorted from smallest to largest.
Click to reveal answer
intermediate
How can you sort a data frame by multiple columns using order()?
Use df[order(df$col1, df$col2), ]. This sorts first by col1, then by col2 within ties.
Click to reveal answer
intermediate
How do you sort in descending order with order()?
Use order(-vec) for numeric vectors. For characters, use order(vec, decreasing = TRUE).
Click to reveal answer
intermediate
Why use order() instead of sort()?
order() gives the positions to rearrange data, useful for sorting data frames or multiple vectors together. sort() just returns a sorted vector.
Click to reveal answer
What does order(c(3,1,2)) return?
A[2, 1, 3]
B[2, 3, 1]
C[3, 1, 2]
D[1, 2, 3]
How do you sort a data frame df by column age ascending?
Adf[order(df$age), ]
Border(df$age)
Csort(df$age)
Ddf[sort(df$age), ]
Which code sorts a vector v in descending order?
Av[order(v)]
Bsort(v)
Cv[order(-v)]
Dorder(v, decreasing=TRUE)
What is the main difference between sort() and order()?
Asort returns sorted values; order returns sorting indices
Border returns sorted values; sort returns indices
CBoth return sorted values
DBoth return sorting indices
How do you sort a data frame by two columns, name then score?
Asort(df$name, df$score)
Bdf[order(df$score, df$name), ]
Corder(df$name, df$score)
Ddf[order(df$name, df$score), ]
Explain how the order() function works and how it differs from sort().
Think about what you get back from each function and how you use it.
You got /4 concepts.
    Describe how to sort a data frame by multiple columns using order().
    Remember how to handle ties in sorting.
    You got /3 concepts.