Part 1

Question 1

Below is a function that ought to return “I’m an even number!” if x is an even number. However, we’re having trouble receiving a value despite x == 4, which we know is an even number. Fix the code chunk and explain why this error is occurring. You will have to change the eval=FALSE option in the code chunk header to get the chunk to knit in your PDF.

NOTE: %% is the “modulo” operator, which returns the remainder when you divide the left number by the right number. For example, try 2 %% 2 (should equal 0 as 2/2 = 1 with no remainder) and 5 %% 2 (should equal 1 as 5/2 = 2 with a remainder of 1).

return_even <- function(x){
  if (x %% 2 == 0) {
    return("I'm an even number!")
  }
}

x <- 4
return_even(x)
## [1] "I'm an even number!"

ANSWER: This is because the code is using return_even() but is missing the x argument, it will not work without the x input or a default value being set. I fixed it by completing the x input like this: return_even(x).

Question 2

R functions are not able to access global variables unless we provide them as inputs.

Below is a function that determines if a number is odd and adds 1 to that number. The function ought to return that value, but we can’t seem to access the value. Debug the code and explain why this error is occurring. Does it make sense to try and call odd_add_1 after running the function?

return_odd <- function(y){
  if (y %% 2 != 0) {
    odd_add_1 <- y + 1
        return(odd_add_1)
  }
}

result <- return_odd(3)
print(result) 
## [1] 4

ANSWER: This is because the variable odd_add_1 was in the function return_odd, so it could not be connected and accessed in the code chunk beyond that function. Also the function does not explicitly return a value, even though odd_add_1 is calculated inside the function. So I added a line to return the results.

Question 3

BMI calculations and conversions: - metric: \(BMI = weight (kg) / [height (m)]^2\) - imperial: \(BMI = 703 * weight (lbs) / [height (in)]^2\) - 1 foot = 12 inches - 1 cm = 0.01 meter

Below is a function bmi_imperial() that calculates BMI and assumes the weight and height inputs are from the imperial system (height in feet and weight in pounds).

df_colorado <- read_csv("data/colorado_data.csv")

bmi_imperial <- function(height, weight){
  bmi = (703 * weight)/(height * 12)^2
  return(bmi)
}

# calculate bmi for the first observation
bmi_imperial(df_colorado$height[1], df_colorado$weight[1])
## [1] 42.62802

Write a function called bmi_metric() that calculates BMI based on the metric system. You can test your function with the Taiwan data set excel file in the data folder, which has height in cm and weight in kg.

bmi_metric <- function(height, weight) {

  height_in_meters <- height * 0.01
  bmi <- weight / (height_in_meters^2)
  return(bmi)
}

df_taiwan <- read_excel("~/PHW251_2024/problem_sets/problem_set_bonus/data/taiwan_data.xlsx")

bmi_metric(df_taiwan$height[1], df_taiwan$weight[1])
## [1] 21.45357

Question 4

Can you write a function called calculate_bmi() that combines both of the BMI functions? You will need to figure out a way to determine which calculation to perform based on the values in the data.

calculate_bmi <- function(height, weight) {
    location <- ifelse(
      "location" %in% names(
        df_colorado) && height %in% df_colorado$height, "Colorado",
                     ifelse(
                       "location" %in% names(
                         df_taiwan) && height %in% df_taiwan$height, "Taiwan",
                            NA))
  
  if (is.na(location)) {
    stop("invalid_location")
  }
  
  if (location == "Colorado") {
    return(bmi_imperial(height, weight))
  } else if (location == "Taiwan") {
    return(bmi_metric(height, weight))
  } else {
    stop("invalid_location")
  }
}


# test
calculate_bmi(df_colorado$height[1], df_colorado$weight[1])
## [1] 42.62802
calculate_bmi(df_taiwan$height[1], df_taiwan$weight[1])
## [1] 21.45357

Question 5

Use your function calculate_bmi() to answer the following questions:

What is the average BMI of the individuals in the Colorado data set?

#my function could not handle vectors so update to
calculate_bmi_vec <- Vectorize(calculate_bmi)

mean_bmi_colorado <- df_colorado %>%
  mutate(bmi = calculate_bmi_vec(height, weight)) %>%
  summarize(mean_bmi = mean(bmi, na.rm = TRUE)) %>%
  pull(mean_bmi)

mean_bmi_colorado
## [1] 45.60881

What is the average BMI of the individuals in the Taiwan data set?

mean_bmi_taiwan <- df_taiwan %>%
  mutate(bmi = calculate_bmi_vec(height, weight)) %>%
  summarize(mean_bmi = mean(bmi, na.rm = TRUE)) %>%
  pull(mean_bmi)

mean_bmi_taiwan
## [1] 22.99287

Question 6

Combine the Colorado and Taiwan data sets into one data frame and calculate the BMI for every row using your calculate_bmi() function. Print the first six rows and the last six rows of that new data set.

#the date columns need to be separated as they cause errors when joining
df_colorado <- df_colorado %>%
  rename(date_colorado = date)
df_taiwan <- df_taiwan %>%
  rename(date_taiwan = date)

df_combined_bmi <- bind_rows(df_colorado, df_taiwan)
df_combined_bmi <- df_combined_bmi %>%
  mutate(bmi = calculate_bmi_vec(height, weight))

head(df_combined_bmi)
tail(df_combined_bmi)

Question 7

Make a boxplot that shows the BMI distribution of the combined data, separated by location on the x-axis. Use a theme of your choice, put a title on your graph, and hide the y-axis title.

NOTE: These data are for practice only and are not representative populations, which is why we aren’t comparing them with statistical tests. It would not be responsible to draw any conclusions from this graph!

ggplot(df_combined_bmi, aes(x = location, y = bmi, fill = location)) +
  geom_boxplot() +
  scale_fill_brewer(palette = "Set2") +
  ggtitle("Mean BMI Data from Colorado and Taiwan") +
  theme_minimal() +
  theme(
    axis.title.y = element_blank(),
    axis.text.x = element_text(angle = 45, hjust = 1)
  )

Part 2

Question 8

Recall the patient data from a healthcare facility that we used in Part 2 of Problem Set 7.

We had four tables that were relational to each other and the following keys linking the tables together:

  • patient_id: patients, schedule
  • visit_id: schedule, visits
  • doctor_id: visits, doctors

Use a join to find out which patients have no visits on the schedule.

no_patient_visits <- patients %>%
  left_join(schedule, by = "patient_id") %>%
  left_join(visits, by = "visit_id") %>%     
  left_join(doctors, by = "doctor_id") %>%    
  filter(is.na(visit_id)) %>%               
  select(patient_id)      

no_patient_visits

Question 9

With this data, can you tell if those patients with no visits on the schedule have been assigned to a doctor? Why or why not?

no_visits_with_doctor <- patients %>%
  left_join(schedule, by = "patient_id") %>%  
  left_join(visits, by = "visit_id") %>%      
  left_join(doctors, by = "doctor_id") %>%  
  filter(is.na(visit_id)) %>%
  select(patient_id, doctor_id)

no_visits_with_doctor %>%
  filter(!is.na(doctor_id))

ANSWER: The doctor_id column in the visits dataset is populated for all entries, whether there is a follow-up or not, and is linked to a specific doctor in the doctor_id column, so I say yes we can determine if those patients with no visit have been assigned to a doctor. I also used code to check this was true.

Question 10

Assume those patients need primary care and haven’t been assigned a doctor yet. Which primary care doctors have the least amount of visits? Rank them from least to most visits.

#I needed to join 3 of the datasets to calculate and rank the visits
doctor_visits <- patients %>%
  left_join(schedule, by = "patient_id") %>%
  left_join(visits, by = "visit_id") %>%
  left_join(doctors, by = "doctor_id")

doctor_visit_counts <- doctor_visits %>%
  group_by(doctor_id, doctor) %>%
  summarise(visits_count = n(), .groups = 'drop')

doctor_visits_ranked <- doctor_visit_counts %>%
  arrange(visits_count)

head(doctor_visits_ranked)

Part 3

Recall in Problem Set 5, Part 2, we were working with data from New York City that tested children under 6 years old for elevated blood lead levels (BLL). [You can read more about the data on their website]).

About the data:

All NYC children are required to be tested for lead poisoning at around age 1 and age 2, and to be screened for risk of lead poisoning, and tested if at risk, up until age 6. These data are an indicator of children younger that 6 years of age tested in NYC in a given year with blood lead levels (BLL) of 5 mcg/dL or greater. In 2012, CDC established that a blood lead level of 5 mcg/dL is the reference level for exposure to lead in children. This level is used to identify children who have blood lead levels higher than most children’s levels. The reference level is determined by measuring the NHANES blood lead distribution in US children ages 1 to 5 years, and is reviewed every 4 years.

Question 11

Load in a cleaned-up version of the blood lead levels data:

Create a formattable table (example below) that shows the elevated blood lead levels per 1000 tested across 2013-2016. If the BLL increases from the previous year, turn the text red. If the BLL decreases from the previous year, turn the text green. To accomplish this color changing, you may want to create three indicator variables that check the value between years (e.g. use if_else). If you’ve have used conditional formatting on excel/google sheets, the concept is the same, but with R.

Note: If you are using if_else (hint hint) and checking by the year, you will likely need to use the left quote, actute, backtip, to reference the variable.

We have also provided you a function that you can use within your formattable table to reference this indicator variable to help reduce the code. However, you do not have to use this, and feel free to change the hex colors.

bll_nyc_per_1000_new <- bll_nyc_per_1000 %>%
  pivot_wider(
    names_from = time_period, values_from = bll_5plus_1k, names_prefix = "bll_")

bll_nyc_per_1000_table <- bll_nyc_per_1000_new %>%
  mutate(
    indicator_1 = if_else(`bll_2013` < `bll_2014`, 0, 1),
    indicator_2 = if_else(`bll_2014` < `bll_2015`, 0, 1),
    indicator_3 = if_else(`bll_2015` < `bll_2016`, 0, 1)
  ) %>%
  select(-indicator_1, -indicator_2, -indicator_3) %>%
  rename_with(~ gsub("bll_", "", .)) %>%
  rename(borough = borough_id)

bll_nyc_per_1000_table_formatted <- bll_nyc_per_1000_table %>%
  formattable(
    list(
      `2013` = formatter("span", style = x ~ style(color = if_else(
        x < lead(x), "#fd626e", "#03d584"))),
      `2014` = formatter("span", style = x ~ style(color = if_else(
        x < lead(x), "#fd626e", "#03d584"))),
      `2015` = formatter("span", style = x ~ style(color = if_else(
        x < lead(x), "#fd626e", "#03d584"))),
      `2016` = formatter("span", style = x ~ style(color = "#03d584"))
    )
  )

bll_nyc_per_1000_table_formatted
borough 2013 2014 2015 2016
Bronx 20.1 18.7 15.7 15.0
Brooklyn 30.2 26.8 22.6 22.3
Manhattan 15.2 14.1 10.6 8.1
Queens 18.2 18.5 15.4 14.3
Staten Island 17.6 17.1 12.0 14.8

Question 12

Starting with the data frame bll_nyc_per_1000 create a table with the DT library showing elevated blood lead levels per 1000 tested in 2013-2016 by borough. Below is an example of the table to replicate.

bll_nyc_per_1000_table <- bll_nyc_per_1000 %>%

    rename(Borough = borough_id, 
         Year = time_period, 
         `BLL>5` = bll_5plus_1k)

datatable(bll_nyc_per_1000_table,
          options = list(
            pageLength = 10,
            dom = 'ftipr',
            autoWidth = TRUE,
            rowCallback = JS(
              "function(row, data, index) {",
              "  if (index % 2 == 0) {",
              "    $(row).css('background-color', '#fce4d6');",
              "  } else {",
              "    $(row).css('background-color', 'white');",
              "  }",
              "}"
            )
          ),
          caption = htmltools::tags$caption(
            style = 'caption-side: top; text-align: center; font-size: 16px; font-weight: bold;',
            'New York City: Elevated Blood Lead Levels 2013-2016 by Borough'
          )
)

Part 4

Question 13

For this question, we will use suicide rates data that comes from the CDC.

Replicate the graph below using plotly.

states_for_plotting <- c("AZ", "CA", "FL", "HI", "MI", "NY", "WY")

df_suicide_filtered <- df_suicide %>%
  filter(STATE %in% states_for_plotting)

line_styles <- list(
  AZ = list(color = "#8FBC8F", dash = "solid"),     
  CA = list(color = "#F4A261", dash = "dash", width = 2),
  FL = list(color = "#D3A8E3", dash = "dot", width = 2),  
  HI = list(color = "#D5006D", dash = "dashdot", width = 2),
  MI = list(color = "#A8D08D", dash = "dash", width = 2), 
  NY = list(color = "#FFEB3B", dash = "dashdot", width = 2),
  WY = list(color = "#D8C3A5", dash = "dash", width = 2)
)

suicide_plot <- plot_ly() 

for(state in states_for_plotting) {
  suicide_plot <- suicide_plot %>%
    add_trace(
      data = df_suicide_filtered %>% filter(STATE == state),
      x = ~YEAR,
      y = ~RATE,
      type = 'scatter',
      mode = 'lines',
      name = state,
      line = line_styles[[state]]
    )
}

suicide_plot <- suicide_plot %>%
  layout(
    title = "Suicide Rates by State Over Time",
    xaxis = list(title = "Year"),
    yaxis = list(
      title = "Suicide Rate per 100,000",
      tickmode = "linear",
      tick0 = 0,
      dtick = 5 
    ),
    showlegend = TRUE
  )

suicide_plot

Question 14

Create an interactive (choropleth) map with plotly similar to the one presented on the CDC website. On the CDC map you can hover over each state and see the state name in bold, the death rate, and deaths. We can do much of this with plotly. As a challenge, use only the 2018 data to create an interactive US map colored by the suicide rates of that state. When you hover over the state, you should see the state name in bold, the death rate, and the number of deaths.

Some key search terms that may help:

  • choropleth
  • hover text plotly r
  • hover text bold plotly r
  • plotly and html
  • html bold
  • html subtitle

Below is an image of an example final map when you hover over California.

Here is the shell of the map to get you started. Copy the plotly code into the chunk below this one and customize it.

# data pulled from CDC website described above 
df_suicide <- read_csv("data/Suicide Mortality by State.csv")
df_suicide_2018 <- df_suicide %>%
  filter(YEAR == 2018)

suicide_map <- plot_ly(df_suicide_2018,
               type = "choropleth",
               locationmode = "USA-states",  
               locations = ~STATE,
               z = ~RATE,   
               hoverinfo = 'location+z+text',  
               text = ~paste(
                 "<b>", STATE, "</b><br>",   
                 "Death Rate: ", RATE, "<br>", 
                 "Deaths: ", DEATHS           
               ),
               colorscale = 'Viridis',       
               colorbar = list(title = "Suicide Rate per 100,000")  
)

suicide_map <- suicide_map %>%
  layout(
    title = "Suicide Rates by State in 2018",
    geo = list(
      scope = "usa",
      projection = list(type = "albers usa"),
      showlakes = TRUE, 
      lakecolor = "rgb(255, 255, 255)"
    )
  )

suicide_map