Answers 01 - dplyr – data wrangling

Author
Affiliations
John R Little

Duke University

Published

January 6, 2023

Setup

  1. Load the tidyverse library package
library(tidyverse)
  1. Import data
brodhead <- read_csv("../../data/brodheadCenter.csv")

exercise_01 – Data Wrangling

  1. Which restaurant has the lowest cost item and what is the item?
brodhead %>% 
  arrange(cost) %>% 
  select(name, type, itemName, cost)

Alternative Answer

lowest_cost_item <- brodhead %>% 
  arrange(cost) %>% 
  select(name) %>% 
  slice_head() %>% 
  pull()
lowest_cost_item  
[1] "Tandoor"

The lowest cost item can be found at Tandoor.

  1. Which restaurant has the most expensive item(s)? What are those item(s)?
brodhead %>% 
  arrange(desc(cost)) %>% 
  select(name, type, itemName, cost)

Alternative Answers

answer2 <- brodhead %>% 
  select(name, type, itemName, cost) %>% 
  filter(type == "restaurant",
         cost == max(cost)) 
answer2
expensive_items <- brodhead %>% 
  select(name, type, itemName, cost) %>% 
  filter(type == "restaurant",
         cost == max(cost)) %>% 
  select(name, itemName) 

expensive_items

Example of inline coding (Render report to see result.)

The Tandoor restaurant offers the following items at the highest cost: lamb korma, beef bhunas, shrimp bhunas.

  1. At the Brodhead Center, how many of the entrees (found in the menuType variable) cost eight dollars?
brodhead %>% 
  filter(cost == 8, menuType == "entree") %>% 
  select(name, menuType, itemName, cost)

The answer is 8. You know this because the Tibble (data frame) has 8 rows.

Alternative Answer

brodhead %>% 
  filter(cost == 8, menuType == "entree") %>% 
  select(name, menuType, itemName, cost) %>% 
  count(menuType)

Alternative Answer

eight_dollar_items <- brodhead %>% 
  filter(cost == 8, menuType == "entree") %>% 
  select(name, menuType, itemName, cost) 

length(eight_dollar_items$itemName)
[1] 8
  1. The head of Duke dining is considering reducing prices at the Brodhead Center. Using what we’ve learned in class, write code that will calculate a new variable (halfPrice) that contains items at half price.
brodhead %>% 
  mutate(halfPrice = (cost / 2)) %>% 
  select(name, itemName, cost, halfPrice) %>% 
  mutate(halfPrice = scales::dollar(halfPrice))
  1. How many entrees are in the dataset (menuType variable)? How many desserts
brodhead %>% 
  count(menuType)
# You can use `filter()` to limit by menuType

Alternative Answer

brodhead %>% 
  count(menuType) %>% 
  filter(menuType == "entree") %>% 
  pull(n)
[1] 24

There are 24 entrees.