Adding new columns with dplyr

Besides performing data manipulation on existing columns, there are situations where a user may need to create a new column for more advanced analysis. In this recipe, we will introduce how to add a new column using dplyr.

Getting ready

Ensure that you completed the Enhancing a data.frame with a data.table recipe to load purchase_view.tab and purchase_order.tab as both data.frame and data.table into your R environment.

How to do it…

Perform the following steps to add a new column to an existing dataset:

  1. First, we calculate the average price of each purchase and add the created result as a column back to the original dataset:
    > order.dt %>%  select(Quantity, Price) %>% mutate(avg_price= Price/Quantity) %>% head()
     Quantity ...

Get R for Data Science Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.