Get Started

Selection of data frame elements

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!

This is a part of the course

“Introduction to R”

View Course

Exercise instructions

  • From planets_df, select the diameter of Mercury: this is the value at the first row and the third column. Simply print out the result.
  • From planets_df, select all data on Mars (the fourth row). Simply print out the result.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# 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)

This exercise is part of the course

Introduction to R

BeginnerSkill Level
4.7+
595 reviews

Master the basics of data analysis in R, including vectors, lists, and data frames, and practice R with real data sets.

Most datasets you will be working with will be stored as data frames. By the end of this chapter, you will be able to create a data frame, select interesting parts of a data frame, and order a data frame according to certain variables.

Exercise 1: What's a data frame?Exercise 2: Quick, have a look at your datasetExercise 3: Have a look at the structureExercise 4: Creating a data frameExercise 5: Creating a data frame (2)Exercise 6: Selection of data frame elements
Exercise 7: Selection of data frame elements (2)Exercise 8: Only planets with ringsExercise 9: Only planets with rings (2)Exercise 10: Only planets with rings but shorterExercise 11: SortingExercise 12: Sorting your data frame

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free