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?✗ Incorrect
The order function returns indices that sort the vector. The smallest element is at position 2 (value 1), then position 3 (value 2), then position 1 (value 3).
How do you sort a data frame
df by column age ascending?✗ Incorrect
You use order to get the sorting indices and then reorder the rows of df accordingly.
Which code sorts a vector
v in descending order?✗ Incorrect
Using negative values with order sorts numeric vectors in descending order.
What is the main difference between
sort() and order()?✗ Incorrect
sort() returns the sorted vector, while order() returns the positions to sort the vector.How do you sort a data frame by two columns,
name then score?✗ Incorrect
You pass multiple columns to order to sort by the first, then the second within ties.
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.