Consider the following R code that sorts a vector using order(). What will be the output?
x <- c(5, 2, 9, 1) sorted_x <- x[order(x)] sorted_x
The order() function returns the indices that would sort the vector.
The order(x) returns the indices that sort x in ascending order: 4, 2, 1, 3. Using these indices to subset x gives the sorted vector c(1, 2, 5, 9).
Given this data frame, what will be the output of ordering by age then score?
df <- data.frame(name=c('Ann', 'Bob', 'Cara', 'Dan'), age=c(25, 25, 22, 25), score=c(90, 85, 88, 85)) ordered_df <- df[order(df$age, df$score), ] ordered_df$name
First sort by age ascending, then by score ascending.
The data frame rows sorted by age then score are: Cara (22,88), Bob (25,85), Dan (25,85), Ann (25,90). Since Bob and Dan have the same age and score, their original order is preserved.
Examine the code below. Why does it produce an error?
x <- c(3, 1, 4) order(x > 2, x)
Check if logical vectors can be used in order().
The order() function can handle logical vectors because they are treated as numeric (FALSE=0, TRUE=1). So no error occurs and it returns indices ordering by x > 2 then x.
Choose the correct R code to sort vector v in descending order using order().
v <- c(10, 5, 8, 3)
Remember order() does not have a decreasing argument; use negative values to reverse order.
order() does not support decreasing argument. Using -v reverses the order. Option D and D are similar but D uses multiplication which works but is less idiomatic. Option D is invalid because order() has no decreasing argument. Option D uses a non-existent argument desc.
Given the vector v <- c(4, 2, 4, 3, 2, 1), how many items are in the vector after sorting with order() and removing duplicates?
v <- c(4, 2, 4, 3, 2, 1) unique_sorted_v <- unique(v[order(v)]) length(unique_sorted_v)
First sort the vector, then remove duplicates, then count the length.
Sorting v gives c(1, 2, 2, 3, 4, 4). Removing duplicates leaves c(1, 2, 3, 4), which has length 4.