0
0
R Programmingprogramming~10 mins

Sorting with order() in R Programming - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to sort the vector nums in ascending order using order().

R Programming
nums <- c(5, 2, 9, 1, 7)
sorted_nums <- nums[[1](nums)]
sorted_nums
Drag options to blanks, or click blank then click option'
Asort
Brank
Cwhich
Dorder
Attempts:
3 left
💡 Hint
Common Mistakes
Using sort() inside the brackets instead of order().
Using rank() which gives ranks, not indices.
Using which() which finds indices of TRUE values.
2fill in blank
medium

Complete the code to sort the data frame df by the column age in ascending order using order().

R Programming
df <- data.frame(name = c("Anna", "Bob", "Cara"), age = c(25, 22, 30))
sorted_df <- df[[1](df$age), ]
sorted_df
Drag options to blanks, or click blank then click option'
Arank
Bsort
Corder
Dwhich
Attempts:
3 left
💡 Hint
Common Mistakes
Using sort() which returns sorted values, not indices.
Using rank() which gives ranks, not indices.
Forgetting the comma after the index to subset rows.
3fill in blank
hard

Fix the error in the code to sort the vector vals in descending order using order().

R Programming
vals <- c(3, 8, 1, 6)
sorted_vals <- vals[[1](-vals)]
sorted_vals
Drag options to blanks, or click blank then click option'
Aorder
Bsort
Crank
Dwhich
Attempts:
3 left
💡 Hint
Common Mistakes
Using sort(-vals) inside brackets which returns values, not indices.
Using rank() which does not give sorting indices.
Using which() which is unrelated here.
4fill in blank
hard

Fill both blanks to sort the data frame df first by score descending, then by age ascending using order().

R Programming
df <- data.frame(name = c("Tom", "Sue", "Jim"), score = c(90, 90, 85), age = c(20, 22, 21))
sorted_df <- df[order([1], [2]), ]
sorted_df
Drag options to blanks, or click blank then click option'
A-df$score
Bdf$score
Cdf$age
D-df$age
Attempts:
3 left
💡 Hint
Common Mistakes
Using df$score instead of -df$score for descending order.
Using -df$age which sorts age descending instead of ascending.
Forgetting the comma after order() arguments.
5fill in blank
hard

Fill all three blanks to create a named vector sorted_vec sorted by values ascending, keeping names, using order().

R Programming
vec <- c(b = 3, a = 1, c = 2)
sorted_vec <- vec[[1](vec)]
names_sorted <- names([2])
result <- setNames([3], names_sorted)
result
Drag options to blanks, or click blank then click option'
Aorder
Bsorted_vec
Cvec
Dnames_sorted
Attempts:
3 left
💡 Hint
Common Mistakes
Using sort() instead of order() for indices.
Mixing up which vector to get names from.
Not using setNames() to keep names with values.