0
0
R Programmingprogramming~20 mins

Sorting with order() in R Programming - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Order Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this R code using order()?

Consider the following R code that sorts a vector using order(). What will be the output?

R Programming
x <- c(5, 2, 9, 1)
sorted_x <- x[order(x)]
sorted_x
A[1] 9 5 2 1
B[1] 5 2 9 1
C[1] 1 2 5 9
D[1] 2 1 5 9
Attempts:
2 left
💡 Hint

The order() function returns the indices that would sort the vector.

Predict Output
intermediate
2:00remaining
What is the output when ordering a data frame by two columns?

Given this data frame, what will be the output of ordering by age then score?

R Programming
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
A[1] "Cara" "Ann" "Bob" "Dan"
B[1] "Cara" "Bob" "Dan" "Ann"
C[1] "Dan" "Bob" "Ann" "Cara"
D[1] "Bob" "Ann" "Dan" "Cara"
Attempts:
2 left
💡 Hint

First sort by age ascending, then by score ascending.

🔧 Debug
advanced
2:00remaining
Why does this order() call produce an error?

Examine the code below. Why does it produce an error?

R Programming
x <- c(3, 1, 4)
order(x > 2, x)
ANo error; returns indices ordering by x > 2 then x
BError because order() expects vectors of the same length and type
CError because logical vector cannot be used directly with numeric vector in order()
DError because > operator is not vectorized
Attempts:
2 left
💡 Hint

Check if logical vectors can be used in order().

📝 Syntax
advanced
2:00remaining
Which option has correct syntax to sort a vector in descending order using order()?

Choose the correct R code to sort vector v in descending order using order().

R Programming
v <- c(10, 5, 8, 3)
Av[order(-1 * v)]
Bv[order(v, decreasing=TRUE)]
Cv[order(v, desc=TRUE)]
Dv[order(-v)]
Attempts:
2 left
💡 Hint

Remember order() does not have a decreasing argument; use negative values to reverse order.

🚀 Application
expert
2:00remaining
How many items are in the sorted vector after removing duplicates?

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?

R Programming
v <- c(4, 2, 4, 3, 2, 1)
unique_sorted_v <- unique(v[order(v)])
length(unique_sorted_v)
A4
B5
C6
D3
Attempts:
2 left
💡 Hint

First sort the vector, then remove duplicates, then count the length.