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.
order()
on planets_df$diameter
(the diameter
column of planets_df
). Store the result as positions
.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!")
order(planets_df$diameter)
to create positions
.positions
inside square brackets: planets_df[...]
; can you fill in the ...
?