How to Analyze Data with R: A Complete Beginner Guide to dplyr


Updated: September 1, 2022.

Datasets often require many work hours to understand fully. R makes this process as easy as possible through the dplyr package – the easiest solution for code-based data analysis. You’ll learn how to use it today.

Are you completely new to R? Here’s our beginner R guide for programmers.

You’ll use the Gapminder dataset throughout the article. It’s available through CRAN, so make sure to install it. Here’s how to load in all required packages:

library(dplyr)
library(gapminder)

head(gapminder)

Here’s what the first couple of rows of the Gapminder dataset looks like:

Image 1 – Gapminder dataset head

And that’s all you need to start analyzing.

Today you’ll learn about:


Column Selection in R dplyr

More often than not, you don’t need all dataset columns for your analysis. R’s dplyr provides a couple of ways to select columns of interest. The first one is more obvious – you pass the column names inside the select() function.

Here’s how to use this syntax to select a couple of columns:

gapminder %>%
  select(country, year, pop)

Here are the results:

Image 2 – Column selection method 1

But what if you have dozens of columns and want to select all but a few? There’s a better way – specify the columns you don’t need with a minus sign (-) as a prefix:

gapminder %>%
  select(-continent)

Here are the results:

Image 3 – Column selection method 2

As you can see, the continent column is the only one that isn’t shown. And that’s all you should know about column selection. Let’s proceed with data filtering.

Data Filtering

Filtering datasets is one of the most common operations you’ll do on your job. Not all data is relevant at a given time. Sometimes you need values for a particular product or its sales figures in Q1. Or both. That’s where the filter() function comes in handy.

Here’s how to display results only for 2007:

gapminder %>%
  select(country, year, lifeExp) %>%
  filter(year == 2007)

The results are shown below:

Image 4 – Data filtering example – year = 2007

You can nest multiple filter conditions inside a single filter() function. Just make sure to separate the conditions by a comma. Here’s how to select a record for Poland in 2007:

gapminder %>%
  select(country, year, lifeExp) %>%
  filter(year == 2007, country == "Poland")

Here are the results:

Image 5 – Data filtering example – year = 2007, country = Poland

But what if you want results for multiple countries? You can use the %in% keyword for the task. The snippet below shows records for 2007 for Poland and Croatia:

gapminder %>%
  select(country, year, lifeExp) %>%
  filter(year == 2007, country %in% c("Poland", "Croatia"))

Here are the results:

Image 6 – Data filtering example – year = 2007, country = (Poland, Croatia)

If you understand these examples, you understand data filtering. Let’s continue with data ordering.

Data Ordering

Sometimes you want your data ordered by a specific column(s) value. For example, you might want to sort users by age or students by score, either in ascending or descending order. You can easily implement this behavior with dplyr – with its built-in arrange() function.

Here’s how to arrange the results by life expectancy:

gapminder %>%
  select(country, year, lifeExp) %>%
  filter(year == 2007) %>%
  arrange(lifeExp)

The results are shown below:

Image 7 – Data ordering example 1

As you can see, data is ordered by the lifeExp column ascendingly. Most cases require descending ordering. Here’s how you can implement it:

gapminder %>%
  select(country, year, lifeExp) %>%
  filter(year == 2007) %>%
  arrange(desc(lifeExp))

Here are the results:

Image 8 – Data ordering example 2

Sometimes you want only a couple of rows returned. The top_n() function lets you specify how many rows should be displayed. Here’s an example:

gapminder %>%
  select(country, year, lifeExp) %>%
  filter(year == 2007) %>%
  arrange(desc(lifeExp)) %>%
  top_n(5)

The results are shown in the following image:

Image 9 – Data ordering example 9

And that’s it with regards to the ordering. Next up – derived columns.

Creating Derived Columns in R dplyr

With R dplyr, you can use the mutate() function to create new attributes. The new attribute name is put on the left side of the equal sign, and the contents on the right – just as if you were to declare a variable.

The example below calculates GDP as a product of population and GDP per capita and stores it in a dedicated column. Some other transformations are made along the way:

gapminder %>%
  select(country, year, pop, gdpPercap) %>%
  filter(year == 2007) %>%
  mutate(gdp = pop * gdpPercap) %>%
  arrange(desc(gdp)) %>%
  top_n(5)

Here are the results:

Image 10 – Calculating GDP as (population * GDP per capita)

Instead of mutate(), you can also use transmute(). There’s one severe difference – transmute() keeps only the derived column. Let’s use it in the example from above:

gapminder %>%
  select(country, year, pop, gdpPercap) %>%
  filter(year == 2007) %>%
  transmute(gdp = pop * gdpPercap) %>%
  arrange(desc(gdp)) %>%
  top_n(5)

The results are shown below:

Image 11 – Calculating GDP with transmute() – all other columns are dropped

You’ll use mutate() more often, but knowing additional functions can’t hurt.

Calculating Summary Statistics

Summary statistics don’t need any introduction. In many cases, you need to calculate a simple average of a column. Here’s how to calculate average life expectancy among the entire dataset:

gapminder %>%
  summarize(avgLifeExp = mean(lifeExp))

Here are the results:

Image 12 – Calculating average life expectancy of the entire dataset

As you would imagine, you can chain other functions to calculate summary statistics only on a subset. Here’s how to calculate the average life expectancy in 2007 in Europe:

gapminder %>%
  filter(year == 2007, continent == "Europe") %>%
  summarize(avgLifeExp = mean(lifeExp))

The results are shown in the following image:

Image 13 – Calculating average life expectancy for Europe in 2007

You can do much more with summary statistics, but that requires some grouping knowledge. Let’s cover that next.

Grouping in R dplyr

Summary statistics become much more powerful when combined with grouping. For example, you can use the group_by() function to calculate the average life expectancy per continent. Here’s how:

gapminder %>%
  filter(year == 2007) %>%
  group_by(continent) %>%
  summarize(avgLifeExp = mean(lifeExp))

Here are the results:

Image 14 – Calculating average life expectancy per continent

You can also use the previously discussed ordering functions to arrange the dataset by average life expectancy. Here’s how to do so in a descending way:

gapminder %>%
  filter(year == 2007) %>%
  group_by(continent) %>%
  summarize(avgLifeExp = mean(lifeExp)) %>%
  arrange(desc(avgLifeExp))

The results are shown below:

Image 15 – Ordering dataset by average life expectancy per continent

One other powerful function is if_else(). You can use it when creating new columns whose value depends on some conditions.

For example, here’s how to create a column named over75, which has a value of Y if the average life expectancy for a continent is over 75, and N otherwise:

gapminder %>%
  filter(year == 2007) %>%
  group_by(continent) %>%
  summarize(avgLifeExp = mean(lifeExp)) %>%
  mutate(over75 = if_else(avgLifeExp > 75, "Y", "N"))

The results are shown in the following image:

Image 16 – Using if_else() upon attribute creation

And that’s all you should know about grouping! Let’s cover data slicing next.

Data Slicing

This is yet another essential concept in R dplyr. Essentially, it allows you to index the dataset rows using a bunch of convenient helper functions. For example, you can use the raw slice() function to select the first N rows, as shown below:

gapminder %>%
  slice(1)

Here are the results – it’s just the first row of the dataset:

Image 17 – Slicing one row

You can also use the slice_head() function to be a bit more verbose. The function displays the first N rows of the dataset, hence the “head” name:

gapminder %>%
  slice_head(n = 3)

Image 18 – Slicing the first 3 rows

The slice_tail() function does the same, but for the other end of the dataset. It will display the bottom N rows instead:

gapminder %>%
  slice_tail(n = 3)

Image 19 – Slicing the last 3 rows

If your dataset is sorted by default, neither of the previous two functions will give a representative sample. There’s another slicing function in R dplyr – slice_sample(), and it’ll display a random sample of N rows:

gapminder %>%
  slice_sample(n = 5)

Image 20 – Slicing a random sample of 5 rows

There’s also a handy slice_min() function. Its job is to extract the N rows with the lowest value for a specified column. Here’s an example – the dataset is firstly filtered to keep only the most recent records, and then 5 rows with the lowest life expectancy are extracted:

gapminder %>%
  filter(year == 2007) %>%
  slice_min(lifeExp, n = 5)

Image 21 – Slicing the bottom 5 rows by life expectancy

As you would expect, there’s also a slice_max() function. It does just the opposite – we think you can get the gist:

gapminder %>%
  filter(year == 2007) %>%
  slice_max(lifeExp, n = 5)

Image 22 – Slicing the top 5 rows by life expectancy

And that’s how you can slice your dataset in R dplyr. Let’s wrap things up next.


Summary of R dplyr

Today you’ve learned how to analyze data with R’s dplyr. It’s one of the most developer-friendly packages out there, way simpler than it’s Python competitor – Pandas. 

You should be able to analyze and prepare any type of dataset after reading this article. You can do more advanced things, of course, but often these are just combinations of the things you’ve learned today.

Learn More