Similar to vectors and matrices, you select elements from a data frame with the help of square brackets [ ]
. By using a comma, you can indicate what to select from the rows and the columns respectively. For example:
my_df[1,2]
selects the value at the first row and second column in my_df
.my_df[1:3,2:4]
selects rows 1, 2, 3 and columns 2, 3, 4 in my_df
.Sometimes you want to select all elements of a row or column. For example, my_df[1, ]
selects all elements of the first row. Let us now apply this technique on planets_df
!
planets_df
, select the diameter of Mercury: this is the value at the first row and the third column. Simply print out the result.planets_df
, select all data on Mars (the fourth row). Simply print out the result.
load(url("http://s3.amazonaws.com/assets.datacamp.com/course/intro_to_r/planets.RData"))
# The planets_df data frame from the previous exercise is pre-loaded
# Print out diameter of Mercury (row 1, column 3)
# Print out data for Mars (entire fourth row)
# The planets_df data frame from the previous exercise is pre-loaded
# Print out diameter of Mercury (row 1, column 3)
planets_df[1,3]
# Print out data for Mars (entire fourth row)
planets_df[4, ]
msg = "Do not remove or overwrite the `planets_df` data frame!"
test_object("planets_df", undefined_msg = msg, incorrect_msg = msg)
test_output_contains("planets_df[1,3]", incorrect_msg = "Have you correctly selected and printed out the diameter for Mercury? You can use `[1,3]`.")
test_output_contains("planets_df[4, ]", incorrect_msg = "Have you correctly selected and printed out all data for Mars? You can use `[4,]`.")
success_msg("Great! Apart from selecting elements from your data frame by index, you can also use the column names. To learn how, head over to the next exercise.")
To select the diameter for Venus (the second row), you would need: planets_df[2,3]
. What do you need for Mercury then?