Sorting your data frame

Alright, now that you understand the order() function, let us do something useful with it. You would like to rearrange your data frame such that it starts with the smallest planet and ends with the largest one. A sort on the diameter column.

Instruction

  • Call order() on planets_df$diameter (the diameter column of planets_df). Store the result as positions.
  • Now reshuffle planets_df with the positions vector as row indexes inside square brackets. Keep all columns. Simply print out the result.
load(url("http://s3.amazonaws.com/assets.datacamp.com/course/intro_to_r/planets.RData")) # planets_df is pre-loaded in your workspace # Use order() to create positions positions <- # Use positions to sort planets_df # planets_df is pre-loaded in your workspace # Use order() to create positions positions <- order(planets_df$diameter) # Use positions to sort planets_df planets_df[positions, ] msg = "Do not remove or overwrite the `planets_df` data frame!" test_object("planets_df", undefined_msg = msg, incorrect_msg = msg) test_object("positions", incorrect_msg = "Have you correctly calculated the `positions` variable? You can use `order(planets_df$diameter)`.") test_output_contains("planets_df[positions,]", incorrect_msg = "Use `planets_df[positions, ]` to sort `planets_df`; the comma inside the square brackets is crucial!") success_msg("Wonderful! This exercise concludes the chapter on data frames. Remember that data frames are extremely important in R, you will need them all the time. Another very often used data structure is the list. This will be the subject of the next chapter!")
  • Use order(planets_df$diameter) to create positions.
  • Now, you can use positions inside square brackets: planets_df[...]; can you fill in the ...?

Previous: 5-11 | Sorting

Next: 6-1 | Lists, why would you need them?

Back to Main