Summer Deals - hours only!Up to 80% off on all courses and bundles.-Close
Introduction to data frames
Data frame structure
Accessing columns in a data frame
Accessing rows and columns combined in a data frame
20. Accessing rows and columns combined
Data frame analysis
Summary

Instruction

Super! Earlier, we mentioned that the bracket operator can be used to filter rows, columns, and both at the same time. So far, to keep things simple, we've looked at just filtering rows and columns separately. Now, we'll move on to filtering both rows and columns simultaneously. The R pseudocode for row and column filtering looks like this:

data.frame.name[condition for row filtering, condition for column filtering]

This actually means that two types of filtering can be defined inside [...] at once as one expression (they will be separated by a comma, of course).

Let's work through an example. If you would like to display the names of cities that have more than 3 million people, you can write the following code:

cities[cities$population > 3000000, "city"]

Inside the square brackets, we defined row filtering with

cities$population > 3000000
After the comma, we filtered columns by specifying the name of the column — in this case, "city". Again, notice that both conditions are separated by a comma inside the square brackets.

Exercise

Using the countries data frame, display the names of countries that have a population density of more than 1000. The information about population density is stored in the pop_density column. The country names are stored in the country column.

Stuck? Here's a hint!

The condition for row filtering will be:

countries$pop_density > 1000

The condition for column filtering will be "country". Place both conditions inside brackets, separated by a comma.