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
.
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.
Perform the following steps to add a new column to an existing dataset:
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 Price avg_price 1: 1 1069 1069 2: 1 1680 1680 3: 1 285 285 4: 1 550 550 5: 1 249 249 6: 1 1780 1780
Alternatively, we can use the
transmute
function...