Learn
Modifying Data Frames in R
Adding Multiple Columns

Let’s refer back to the inventory table for your store, The Handy Woman.

product_id product_description cost_to_manufacture price sales_tax
1 3 inch screw 0.50 0.75 0.06
2 2 inch nail 0.10 0.25 0.02
3 hammer 3.00 5.50 0.41
4 screwdriver 2.50 3.00 0.22

You want to add two more new columns to your table. One column will contain the profit made from selling each item (price - cost_to_manufacture), and the other will state whether the item is currently in stock (suppose every item is currently in stock).

mutate() can take multiple arguments to add any number of new columns to a data frame:

df %>% mutate(profit = price - cost_to_manufacture, in_stock = TRUE)
  • mutate() takes two arguments, defining new columns profit and in_stock
  • profit is equal to price minus cost_to_manufacture
  • in_stock, rather than be derived from values in existing columns, is given the value TRUE for all rows

The inventory table will now look like this:

product_id product_description cost_to_manufacture price sales_tax profit in_stock
1 3 inch screw 0.50 0.75 0.06 0.25 TRUE
2 2 inch nail 0.10 0.25 0.02 0.15 TRUE
3 hammer 3.00 5.50 0.41 2.5 TRUE
4 screwdriver 2.50 3.00 0.22 0.5 TRUE

Instructions

1.

Update the call to mutate() by adding an additional argument that adds a new column avg_weight that is the average of weight_low_lbs and weight_high_lbs.

Use head() to inspect the new data frame.

2.

You want to see how the popularity of dog breeds has changed from 2013 to 2016. The change in rank can be calculated by subtracting the earlier rank from the later rank.

Update the call to mutate() by adding one last argument that adds a new column rank_change_13_to_16 that is the change in rank from 2013 to 2016 (rank_2016 - rank_2013).

Folder Icon

Take this course for free

Already have an account?