Complete the code to sort the vector nums in ascending order using order().
nums <- c(5, 2, 9, 1, 7) sorted_nums <- nums[[1](nums)] sorted_nums
sort() inside the brackets instead of order().rank() which gives ranks, not indices.which() which finds indices of TRUE values.The order() function returns the indices that would sort the vector. Using these indices to subset nums gives the sorted vector.
Complete the code to sort the data frame df by the column age in ascending order using order().
df <- data.frame(name = c("Anna", "Bob", "Cara"), age = c(25, 22, 30)) sorted_df <- df[[1](df$age), ] sorted_df
sort() which returns sorted values, not indices.rank() which gives ranks, not indices.Using order(df$age) returns the row indices that sort the age column. Subsetting df by these indices sorts the data frame by age.
Fix the error in the code to sort the vector vals in descending order using order().
vals <- c(3, 8, 1, 6) sorted_vals <- vals[[1](-vals)] sorted_vals
sort(-vals) inside brackets which returns values, not indices.rank() which does not give sorting indices.which() which is unrelated here.Using order(-vals) returns indices that sort vals in descending order. Subsetting vals by these indices gives the descending sorted vector.
Fill both blanks to sort the data frame df first by score descending, then by age ascending using order().
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
df$score instead of -df$score for descending order.-df$age which sorts age descending instead of ascending.order() arguments.To sort score descending, use -df$score. To sort age ascending, use df$age. The order() function sorts by the first argument, then the second.
Fill all three blanks to create a named vector sorted_vec sorted by values ascending, keeping names, using order().
vec <- c(b = 3, a = 1, c = 2) sorted_vec <- vec[[1](vec)] names_sorted <- names([2]) result <- setNames([3], names_sorted) result
sort() instead of order() for indices.setNames() to keep names with values.Use order(vec) to get indices that sort vec. Subset vec by these indices to get sorted_vec. Then get names from sorted_vec and assign them back to the sorted values sorted_vec using setNames().