library(tidyverse)Answers 01 - dplyr – data wrangling
Setup
- Load the
tidyverselibrary package
- Import data
brodhead <- read_csv("../../data/brodheadCenter.csv")exercise_01 – Data Wrangling
- 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.
- 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))
answer2expensive_items <- brodhead %>%
select(name, type, itemName, cost) %>%
filter(type == "restaurant",
cost == max(cost)) %>%
select(name, itemName)
expensive_itemsExample 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.
- At the Brodhead Center, how many of the entrees (found in the
menuTypevariable) 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
- 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))- How many entrees are in the dataset (
menuTypevariable)? How many desserts
brodhead %>%
count(menuType)# You can use `filter()` to limit by menuTypeAlternative Answer
brodhead %>%
count(menuType) %>%
filter(menuType == "entree") %>%
pull(n)[1] 24
There are 24 entrees.