---
title: "A spatial and demographic analysis of cycling safety perceptions: A case study in Eau Claire, Wisconsin, USA"
author: 
  - name: "Matthew Haffner"
    affiliation: "University of Wisconsin - Eau Claire, Eau Claire, USA"
  - name: "Nathan Walker"
    affiliation: "Southern Illinois University Edwardsville, Edwardsville, USA"
  - name: "Savanna Grunzke"
    affiliation: "University of Wisconsin - Eau Claire, Eau Claire, USA"
  - name: "Matthew St. Ores"
    affiliation: "University of Wisconsin - Eau Claire, Eau Claire, USA"
bibliography: 480.bib
execute: 
  warning: true
always_allow_html: true
number-sections: true
format: 
  html:
    css: REGION-html.css
    code_fold: true
    code-summary: "Show the code"
abstract: "Bike-friendly cities offer scores of benefits to both individuals and society, but a lack of safety is a major barrier to ridership. Significant research has been devoted to studying demographic drivers of ridership and what makes individuals feel unsafe on a bicycle, but there is lack of research utilizing quantitative approaches on spatial perceptions of safety, particularly with respect to gender. This paper seeks to close that gap using a crowdsourcing approach to spatial data collection, statistical comparisons of cycling behavior by gender, and spatial analyses of mapped points. The authors find parity between women and men in terms of number of trips taken per week but find significant differences in the spatial extent of mapped responses. This paper adds to academic discussions on cycling safety and sheds light on specific locations that could benefit from infrastructure improvements."
---

```{r}
#| label: setup
#| echo: false
#| message: false
#library(RefManageR)
library(here)
library(knitr)
library(sf)
library(dplyr)
library(leaflet)
library(ggplot2)
library(stringr)
library(units)
library(tmap)
library(dbscan)
library(purrr)
library(readr)
library(magrittr)
library(kableExtra) ## causes problem in LaTeX
library(RColorBrewer)
library(DT)
library(tidyr)

#BibOptions(check.entries = TRUE,
#           bib.style = "authoryear",
#           cite.style = "apa",
#           style = "markdown",
#           hyperlink = TRUE,
#           dashed = FALSE)

#bib <- ReadBib(file = here::here("manuscript/references.bib"))

## set tmap mode to interactive viewing
tmap_mode("view")

female_color <- "#72FB80"
male_color <- "#8072FB"
other_color <- "#FB8072"

age_color_1 <- brewer.pal(n = 12, "Set3")[12] #"#FFED6F"
age_color_2 <- brewer.pal(n = 12, "Set3")[4] #"#FB8072"
age_color_3 <- "#6FFFED"

## retrieve spatial data
pts <- st_read("https://gitlab.com/mhaffner/data/-/raw/master/cycling-safety-points.geojson", quiet = TRUE)

## retrieve tabular data
df <- read_csv("https://gitlab.com/mhaffner/data/-/raw/master/cycling-safety-df.csv")
```

```{css, echo=FALSE}
.legend {
    text-align: left;
}
.leaflet-control {
    text-align: left;
}
```

# Introduction

Bikeable communities provide numerous benefits for citizens. It is well established that cycling produces positive health outcomes for individuals and reduces pollution [@Pucher2010]. Cycling also produces psychological and social benefits [@Xu2019] and is a decidedly safe form of transportation barring encounters with automobiles. Additionally, a growing body of literature suggests significant economic benefits to de-emphasizing vehicular traffic in favor of other modes through greater local business revenue [@NYCDOT2013], increased property values [@Litman1999], and tourism-related opportunities for municipalities [@Blondiau2016]. Alternative and moderately active forms of transportation have also long been shown to promote public health [@Frank2001]. Yet, there remain considerable barriers to creating bike-friendly communities.

A lack of safety has consistently been shown to be a major deterrent to cycling for both potential and current cyclists [@Iwinska2018; @Aldred2017]. Thus, identifying where and why cyclists feel unsafe is crucial to improving bikeability. In this article, the authors present a study on spatial perceptions of cycling safety in an Upper Midwest US city: Eau Claire, Wisconsin. Given the gender disparity of cycling rates in the United States [@Pucher2011], the study pays particular attention to the differing perceptions of women and men. While considerable research has been conducted on cycling shares by demographic categories -- which this paper adds to -- this study is unique in specifically comparing gender differences in *spatial perception*.

Perceptions of cycling safety vary based on spatial context. Encounters with motor vehicles, fear of crime, and adverse weather conditions all pose significant threats [@Rybarcyzk2014]. Specific locations lacking designated bike paths exacerbate these concerns as cars are in closer proximity to cyclists [@Gadsby2022]. Perceptions of infrastructure safety vary demographically. Women in particular show preferences for well-protected bike lanes and tend to perceive roads as more dangerous, preferring shorter travel distances and avoiding areas with steep slopes [@Manton2016; @Misra2018; @Hood2013]. Factors like enclosed spaces, poorly lit streets, and limited visibility are also more concerning for women due to their potential to conceal threats [@Xie2018].

Due to these differences and the dearth of literature on quantitative approaches to spatial perceptions of cycling safety particularly related to gender, this study seeks to close that gap. The authors first provide a brief review of the relevant literature and then discuss the study's methodology. To collect data, the authors created a web-based survey application to collect both demographic information and volunteered points the respondent perceived as unsafe. The demographic information is used to carry out statistical tests by gender on riding confidence, the influence of safety on where the respondent rides, and the number of cycling trips per week. The authors then use the DBSCAN algorithm to analyze the identified points perceived as unsafe and identify clusters, before creating convex hulls to compare minimum bounding geometry by gender. The results are analyzed and discussed before the authors present the final conclusions and significance of the study. Further, in line with greater calls for a process-based approach to geographic information science [@Shannon2018], the authors leverage the power of JavaScript-driven interactive maps and sortable tables within the body of the paper and encourage readers to explore the data for themselves.

# Background

## Deterrents to cycling

Previous studies have identified many reasons why cyclists may be deterred from riding, of which many revolve around safety. Given that the quality and style of cycling infrastructure can vary greatly, both between and within countries, context is important when synthesizing the literature. That said, some ubiquitous reasons can be found across spatial contexts. Encounters with motor vehicles are a consistent primary barrier to cycling [@Iwinska2018; @Rybarcyzk2014; @Ahmed2013; @Jacobsen2009]. The danger posed by fast-moving automobiles can result in disastrous consequences for the cyclist if a collision occurs, and both cyclists and drivers of motor vehicles exhibit a dislike of interacting with operators of opposing vehicle types [@Griffin2020]. Aside from the risk associated with crashes, traffic is deemed unpleasant to be near due to noise and exhaust pollutants output by vehicles [@Jacobsen2009]. These factors lead to a general fear of injury and a reluctance to ride in car-centric societies [@Iwinska2018].

In addition to the threat of motor vehicles, crime and adverse weather conditions are two other significant barriers to cycling [@Rybarcyzk2014]. Anticipations of crime may cause cyclists to fear for their health, safety, or the loss of their bike due to theft. The threat of crime deterring cycling is observed across demographic groups, significantly affecting behavior in all but the most regular cyclists. [@Wang2018; @Rybarcyzk2014]. Areas with many vacant homes or locations where transportation modes interconnect -- such as train stations where bikes may be locked but left unattended -- exhibit higher rates of cycling-related crime [@Mburu2016]. In other cases, a lack in the proper removal of winter precipitation leads to lower ridership [@Iwinska2018; @Ahmed2013].

In other instances, feelings of insecurity are tied to specific locations and infrastructure types rather than general feelings of trepidation. It has been demonstrated that policies focused on improving and creating relevant infrastructure have all contributed to increases in cycling rates in the present alternative transportation "renaissance" [@Pucher2011], so it follows that infrastructure warrants special attention. While not completely detached from the fear of motor vehicles, a lack of necessary infrastructure leads to higher perceived risk, as the built environment offers fewer accommodations for potential cyclists.

Intersections, for instance, are common locations for possible conflict between cyclists and motor vehicles [@Wang2018; @Digiola2017]. When cars and cyclists are forced to meet at intersections, additional infrastructure such as roundabouts, paved shoulders, or designated bike paths can alleviate concerns of crashes. Further, traffic proximity has been linked to negative perceptions, and areas with a higher concentration of paths distanced from roads have been shown to exhibit higher cycling rates [@Carrol2020; @Branion-Calles2019; @Aldred2017]. This distancing reduces the perceived threat from cars by adding space that reduces the chance of a collision. Potholes, cracks, and other deformities in paved cycling spaces also deter cyclists by reducing safety and increasing levels of discomfort [@Gadsby2022]. These reasons collectively speak to the need for building and maintaining dedicated cycling infrastructure.

## Demographics and cycling safety perceptions

Cities in North America have recently witnessed a growth in the number and frequency of trips by bike. However, this growth has not been experienced equally across the entire population. While the number of male cyclists aged 25-64 has increased dramatically, cycling rates among women and children have not exhibited the same pattern [@Pucher2011]. Present research identifies both physical and cultural reasons for these disparities.

As described in the previous subsection, the quality of cycling infrastructure has a significant impact on both perception and behavior. However, evidence indicates infrastructure does not affect demographic groups equally. Women, the elderly, and those under 18 are all more likely to use well-protected bike lanes rather than infrastructure in closer proximity to cars [@Aldred2017; @Misra2018]. Women are also more likely to perceive a road to be dangerous, travel shorter distances, and avoid areas with steep slopes [@Manton2016; @Misra2018; @Hood2013]. Enclosed spaces, poorly lit streets, and objects that limit visibility also tend to be of greater concern for women, as these manifestations could hide potential threats [@Xie2018].

In addition to the physical environment, studies on cycling safety perception suggest that cultural and social factors drive gender differences. In countries with low cycling rates, such as the US, men are generally more likely to ride bikes and consider cities to be safe for cycling [@Branion-Calles2019; @Aldred2016]. Women tend to have overall lower tolerance for risk than men in a variety of circumstances related to motor vehicles such as when cycling, when driving a vehicle, and in interacting with cyclists [@Griffin2020]. Women are more concerned about bullying and harassment when cycling than men, and as a result alter their routes accordingly [@Graystone2022]. However, in countries with high cycling rates -- like the Netherlands, Denmark, Germany, and Japan -- rates of women that cycle equal or even exceed the rates of men [@Aldred2016; @Goel2021]. In particular, one recent study finds that almost all places where cycling represents at least eight percent of the transportation mode of travel have equal or overrepresentation of female cyclists [@Goel2021]. This suggests that as countries or cities invest in cycling infrastructure as a legitimate alternative to automobile transport, the gender disparity shrinks and can even reverse. In spaces such as the US and Australia, where cycling infrastructure is largely an afterthought to automobile infrastructure, cycling rates remain low and the gender disparity has grown [@Pucher2011].

## Methods of studying cycling safety perceptions

Given that general perceptions of cycling safety are driven by an array of factors, previous studies have used a variety of data collection methods to understand safety perceptions both qualitatively and quantitatively. Most studies involve two components: (1) an analysis of the infrastructure available to cyclists and (2) the self-reported safety perception of the individual. It is common to study responses using in-person [@Iwinska2018; @Manton2016] or online surveys [@Wang2018; @Rybarcyzk2014; @Branion-Calles2019], or in some cases, a combination of the two [@Manaugh2017].

In a comprehensive literature review, Digiola et al. [@Digiola2017] categorized previous work into three groups based on the type of data utilized to perform analysis on cycling safety. These include exposure data, roadway characteristic data, and crash data or "other surrogate measures." Bicycle exposure data is used to estimate the frequency at which cyclists are exposed to risk. This could include bike travel distance, traffic exposure, or percentage of the population that travels by bike. Bicycle exposure can be used to estimate frequency of crashes based on how far the individual rides [@Guo2018], or the amount of exposure to roads with trees can help in predicting the amount of bicycle theft [@Mburu2016].

Exposure data is commonly used in tandem with roadway characteristic data. These datasets can be used to demonstrate the relationships between objects of interest and cycling risk, and data on bicycle crashes is often used as a proxy for estimating risk [@Digiola2017]. This data, when combined with other sources, can be used to produce a prediction model of cycling risk [@Yiann2012; @Guo2018]. Individual independent variables and their influence on resulting models allow for the determination of significant factors leading to crashes. The presence of intersections, narrow roads, bus and tram routes, hills, and curves are all shown to have a positive correlation with cycling risk using this approach [@Morrison2019; @Wang2018; @Aldred2017; @Misra2018; @Branion-Calles2019]. Other studies use mental mapping techniques and have participants annotate a map [@Manton2016].

# Methods and data

Few studies, aside from Manton [@Manton2016], analyze spatial patterns in perceived cycling safety. The approach put forth in the present article has some similarities but is unique in several ways. First, the authors created and distributed a custom, free and open-source web application for the collection of data. Second, the authors focus on demographic differences in perceptions of cycling safety, particularly gender.

Specifically, the study addresses the following questions:

1.  How do non-spatial survey responses differ by gender?

2.  What are the general spatial patterns of unsafe cycling locations?

3.  Where are clusters of perceived unsafe places for cycling located in Eau Claire?

4.  How do spatial responses differ by gender?

Each of the four questions has a dedicated subsection in the *Results* section. The first question is addressed using a series of two-sample Mann-Whitney $U$ tests. This is a non-parametric alternative to the two-sample $t$-test which can be used when the assumption of normality is violated. Additionally, this test can be used with ordinal data, including grouped numeric categories like number of trips per week. While a plethora of statistical tests could be conducted with the collected results, response limitations in demographic categories other than gender precluded the completion of additional comparisons.

To address the second question, the authors use interactive web maps and a heat map. To address the third question, the authors use density-based spatial clustering of applications with noise (DBSCAN). The DBSCAN algorithm searches for a specified minimum number of points within a defined search distance and groups them if they meet requirements. Not all points are grouped into clusters, thus separating "signal" from "noise". Using DBSCAN in an ad hoc manner like this is more of an art than a science; a researcher must balance the input parameters to produce clusters which help make sense of the data. Increasing the minimum number of points -- and/or reducing the search distance -- can greatly reduce the number of clusters. Conversely, reducing the minimum number of points and/or increasing the search distance increases the number of clusters, potentially to an unhelpful number. To address the fourth question, the authors compare clusters of unsafe points using DBSCAN but group responses by gender. Additionally, the authors compare convex hulls (i.e., minimum bounding geometries) by gender as well. The answers to the research questions -- in connection with the authors' local knowledge -- are discussed with respect to the relationship between urban form, transportation infrastructure, and perception.

## Survey instrument and software

To complete this study, a custom web survey was created using the R Project for Statistical Computing and its web framework, Shiny [@Shiny2022]. The survey was hosted on ShinyApps.io and administered to residents of Eau Claire, Wisconsin. An IRB-approved cover letter was obtained and embedded in a web page with a link to the survey included at the bottom of the page. The web survey consists of three tabs, each designating different sections of the survey (see @fig-webapp).

The first tab, containing a web map centered on Eau Claire, Wisconsin, contains a pane with the following instructions:

- 1a. First, select locations which you feel are notably unsafe for cycling near routes where you ride in Eau Claire. Start by clicking once on the map icon (just below the zoom control on the map). Then, click on the map to place a marker. You'll notice a checklist appears below the map. Select a reason for why that location is unsafe.

- 1b. Repeat for as many locations as you feel are necessary.

- 2. Then, click the 'Neighborhood' tab and select the square which corresponds to your approximate home location.

- 3. To complete the survey, click on 'Questions' tab and select your responses there. When you are finished, click on the 'Submit Response' button below the final question.

```{r}
#| label: fig-webapp
#| echo: TRUE
#| fig-align: center
#| fig-cap: "A screenshot of the web app developed for survey implementation with several example spatial responses"
#| code-fold: true
#| code-summary: "Show the code"

knitr::include_graphics(here("img/survey.png"), dpi=400)
```

Careful consideration went into framing the first item in particular. The authors specifically chose the language "Select locations which you feel are notably unsafe for cycling *near routes where you ride* ..." (emphasis added) for two reasons. First, the authors wanted to avoid the possibility of respondents simply putting markers on places which are clearly unsafe but also are not feasible riding locations, such as interstate highways. Second, the authors sought to get a sense of where respondents actually ride, rather than have them label spots distant from their typical riding locations and thus not reflective of where potential infrastructure improvements might benefit the greatest number of cyclists.

The list of reasons for why respondents may feel unsafe was comprised of the following:

-   Lacking or poor infrastructure
-   Traffic proximity
-   Traffic volume
-   Traffic speed
-   Poor visibility from motorists
-   Potential conflicts with pedestrians
-   Steep hills
-   Other

The second tab contains another web map but with a grid of 1 mile x 1 mile squares where participants were instructed to click on the grid cell of their primary residence. This item was included to understand how responses might be biased by where respondents live. The third tab contains the following demographic and cycling behavior questions:

-   How confident do you feel in your cycling ability? Assume 7 is 'Very confident' and 1 is 'Not confident'.
-   How much does safety influence where you ride? Assume 7 is 'Very much' and 1 is 'Not at all'.
-   Approximately how many trips do you take by bike per week?
-   How often do you wear a helmet when riding a bike?
-   For what reasons do you ride a bike? Select all that apply.
-   What is your age?
-   What is your race? You may select more than one option.
-   What is your gender?

Other data was collected on the user's device characteristics, such as whether the survey was completed on mobile or on a desktop computer, along with operating system and screen size.

## Study area: Eau Claire, Wisconsin

This study was implemented in Eau Claire, Wisconsin, located in the Upper Midwest of the United States. This city is the largest municipality in its county and metropolitan area, and it is home to a regional public university, the University of Wisconsin - Eau Claire, which has around 9500 students. While selected in part due to convenience and the authors' familiarity with the city, it is undeniably cycling-friendly compared to many other similarly sized US cities. The city possesses nearly 29 miles of separated bike trails, numerous bicycle lanes, and 8 car-free bridges [@Ec2022]. Despite this, like most other US cities, the vast majority of trips are taken by personal automobile, and much of the transportation infrastructure is not suitable for bicycles.

```{r}
#| label: fig-ecmap
#| echo: TRUE
#| fig-align: center
#| fig-cap: "Location of Eau Claire, Wisconsin, USA"
#| code-fold: true
#| code-summary: "Show the code"

library(webshot2)

leaflet() %>%
  addTiles() %>%
  setView(lng = -91.49925, lat = 44.8090, zoom = 10) %>%
  ## add inset map
  addMiniMap(
    position = 'bottomright',
    width = 200,
    height = 200,
    toggleDisplay = FALSE,
    zoomLevelOffset = -8)
```

## Survey Distribution

The survey was disseminated in the community through a combination of methods in August and September of 2021. Respondents were first recruited through simple word-of-mouth. Acquaintances of the research team who ride a bike were encouraged to complete and share the survey. Fliers with QR codes and links to the survey were posted around the university campus, on social media sites such as Facebook, and distributed in local businesses. In an additional effort to reach the community, the research team on several occasions spent time intercepting cyclists in public parks and on commonly traveled bike trails. Additionally, approximately 300 fliers were taped to bicycles parked on bike racks at apartment buildings, near local businesses, and on campus. In total, 339 unsafe points were mapped by 99 unique individuals.

# Results

Of the respondents, 43 are female, 52 are male, 3 respondents selected "Other" for gender, and 1 respondent neglected this response item. The percentage of female respondents is notably higher than those of other studies, likely explained by the female-heavy gender ratio of the university where many survey fliers were distributed. The largest age category, ages 18 – 23, had 63 responses, ages 25-34 had 13 responses, ages 35-44 had 10 responses, ages 45-54 had 8 responses, and the categories 55-64 and 65+ each had 2 responses.

The racial and ethnic makeup of the survey population roughly mimics the demographics of the city of Eau Claire and is thus relatively homogeneous. Specifically, 92 of the respondents selected a race of White, 4 selected Asian, 4 selected Hispanic, 3 selected Black, 2 selected Indian, 1 selected Hawaiian, and 1 selected Other (See @tbl-demographics for a summary of demographic data and 
[@tbl-survey-data-html for all data points.)]{.content-visible when-format="html"} 
[@tbl-survey-data-pdf for the first ten data points and eight variables.)]{.content-visible when-format="pdf"}

```{r}
#| label: tbl-demographics
#| tbl-cap: "Survey respondent demographics"
#| echo: true
#| eval: true
#| message: false
#| warning: false
#| code-fold: true
#| code-summary: "Show the code"

df_race <- df %>%
  select(white, asian, hispanic, black, indian, hawaiian, other) %>%
  colSums() %>%
  data.frame() %>%
  add_rownames(var = "topic") %>%
  set_colnames(c("topic", "count")) %>%
  transmute(topic = str_to_title(topic), count=count)

df_gender <- df %>%
  group_by(gender) %>%
  count() %>%
  set_colnames(c("topic", "count"))

df$age <- as.factor(df$age)

df_age <- df %>%
  group_by(age) %>%
  count() %>%
  set_colnames(c("topic", "count"))

df_demographics <- rbind(df_race, df_gender, df_age)

kbl(df_demographics,
  booktabs=TRUE, linesep = c(""),
  col.names = c("Topic", "Count")) %>%
  pack_rows("Race", 1, nrow(df_race)) %>%
  pack_rows("Gender", nrow(df_race)+1, nrow(df_race)+nrow(df_gender)) %>%
  pack_rows("Age", nrow(df_race)+nrow(df_gender)+1, nrow(df_demographics))
```

::: {.content-visible when-format="pdf"}
```{r}
#| label: tbl-survey-data-pdf
#| tbl-cap: "Survey data"
#| echo: true
#| eval: true
#| message: false
#| warning: false

columns <- c("Level of confidence in cycling",
             "Safety influence on riding locations",
             "Number of trips per week",
             "Helmet usage",
             "Age",
             "Gender",
             "Race (Black)",
             "Race (Asian)",
             "Race (Hispanic)",
             "Race (Hawaiian)",
             "Race (Indian)",
             "Race (White)",
             "Race (Other)",
             "Cycling for recreation",
             "Cycling for exercise",
             "Cycling for transportation",
             "Device type",
             "Browser",
             "Operating System",
             "Browser width",
             "Browser height")

kbl(df[1:10,c(1:6,8:9)],
    colnames = columns, align=rep('c',8),
    booktabs=TRUE, linesep = c(""))
```
:::

::: {.content-visible when-format="html"}
```{r}
#| label: tbl-survey-data-html
#| tbl-cap: "Survey data"
#| echo: true
#| eval: true
#| message: false
#| warning: false
#| code-fold: true
#| code-summary: "Show the code"

columns <- c("Level of confidence in cycling",
             "Safety influence on riding locations",
             "Number of trips per week",
             "Helmet usage",
             "Age",
             "Gender",
             "Race (Black)",
             "Race (Asian)",
             "Race (Hispanic)",
             "Race (Hawaiian)",
             "Race (Indian)",
             "Race (White)",
             "Race (Other)",
             "Cycling for recreation",
             "Cycling for exercise",
             "Cycling for transportation",
             "Device type",
             "Browser",
             "Operating System",
             "Browser width",
             "Browser height")

datatable(df %>% select(-c(grd_id)),
          colnames = columns)
```
:::


## Non-spatial comparisons by gender

```{r}
#| label: stat-tests
#| echo: true
#| eval: true 
#| message: false
#| warning: false

## get number of trips as a factor (for mann whitney u-test) and 
## numeric (for density plot)
df$number_of_trips_factor <- df$number_of_trips %>%
  as.factor()

levels(df$number_of_trips_factor) <- c("0-3", "4-7", "8-12", "13-20", "20+")
df$number_of_trips_num <- df$number_of_trips_factor %>%
  as.numeric()

df_female <- df %>% filter(gender == "Female")
df_male <- df %>% filter(gender == "Male")

conf_by_gender <- wilcox.test(df_female$confidence, df_male$confidence)
infl_by_gender <- wilcox.test(df_female$safety_influence, 
                              df_male$safety_influence)
trips_by_gender <- wilcox.test(df_female$number_of_trips_num, 
                               df_male$number_of_trips_num)
```

To address the perceptual differences in cycling by gender, the authors compare responses to the following three survey questions:

-   How confident do you feel in your cycling ability? Assume 7 is 'Very confident' and 1 is 'Not confident'.
-   How much does safety influence where you ride? Assume 7 is 'Very much' and 1 is 'Not at all'.
-   Approximately how many trips do you take by bike per week?

Further, the authors also compare the number of unsafe points mapped by each respondent by gender.

As shown in @fig-confbygender, men visually have higher confidence levels than women. This is confirmed through a Mann-Whitney $U$-test ($p$ = `r conf_by_gender$p.value %>% round(3)`) which is used as an alternative to a two-sample $t$-test due to the non-normal shape of the two distributions (see @tbl-stat-results). Similarly, a separate Mann-Whitney $U$-test, ($p$ = `r infl_by_gender$p.value %>% round(3)`) reveals a statistically significant difference in how safety influences riding locations, with safety influencing riding locations for women more than men (see @fig-infl-by-gender).

```{r}
#| label: fig-confbygender
#| echo: true
#| eval: true
#| message: false
#| warning: false
#| fig-cap: "Level of cycling confidence by gender (1 = not confident, 7 = very confident)"
#| code-fold: true
#| code-summary: "Show the code"

ggplot(df %>%
       select(gender, confidence) %>%
       filter(gender %in% c("Female", "Male")) %>%
       gather(gender, confidence) %>%
       transmute(Gender = gender, Confidence = confidence),
       aes(x = Confidence, fill = Gender)) +
  geom_density(alpha = 0.5) +
  xlab("Level of confidence in riding") +
  ylab("Density") +
  scale_fill_manual(values = c(female_color, male_color))
```

```{r}
#| label: fig-infl-by-gender
#| echo: true
#| eval: true
#| message: false
#| warning: false
#| fig-cap: "Influence of safety on choice of riding locations by gender (1 = not at all, 7 = very much)"
#| code-fold: true
#| code-summary: "Show the code"

ggplot(df %>%
       select(gender, safety_influence) %>%
       filter(gender %in% c("Female", "Male")) %>%
       gather(gender, safety_influence) %>%
       transmute(Gender = gender, `Safety influence` = safety_influence),
       aes(x = `Safety influence`, fill = Gender)) +
  geom_density(alpha = 0.5) +
  xlab("Influence of safety on riding locations") +
  ylab("Density") +
  scale_fill_manual(values = c(female_color, male_color))
```

```{r}
#| echo: true
#| eval: true
#| message: false
#| warning: false

num_pts_female <- pts %>%
  filter(gender == "Female") %>%
  pull(user) %>%
  table() %>%
  as.numeric()

num_pts_male <- pts %>%
  filter(gender == "Male") %>%
  pull(user) %>%
  table() %>%
  as.numeric()

num_pts_df <- data.frame(num_points = c(num_pts_female, num_pts_male),
                 gender = c(rep("Female", length(num_pts_female)),
                            rep("Male", length(num_pts_male))))

num_pts_by_gender <- wilcox.test(num_pts_female, num_pts_male)
```

Statistically, there is no difference in the means of the number of points produced by women and men according to a Mann Whitney $U$-test ($p$ = `r num_pts_by_gender$p.value %>% round(3)`), which is perhaps surprising given the number of other gender differences. The means are `r mean(num_pts_female)` for women and `r mean(num_pts_male)` for men, respectively. The right skewed distributions indicate that women and men notably both exhibit the "long tail effect" -- that is, the phenomenon that a small number of users produce a disproportionate amount of content [@Elwood2013]. Both women and men have one "power user", producing `r max(num_pts_female)` points and `r max(num_pts_male)` points, respectively.

```{r}
#| label: fig-num-pts-gender
#| echo: true
#| eval: true
#| message: false
#| warning: false
#| fig-cap: "Number of unsafe points mapped"
#| code-fold: true
#| code-summary: "Show the code"

ggplot(num_pts_df %>% transmute(`Number of points` = num_points,
                        Gender = gender),
     aes(x = `Number of points`, fill = Gender)) +
  geom_density(alpha = 0.5) +
  xlab("") +
  ylab("Density") +
  scale_fill_manual(values = c(female_color, male_color))
```

Similar to the number of points produced by gender, there are not statistical differences in the number of trips taken per week according to a Mann-Whitney $U$-test ($p$ = `r trips_by_gender$p.value %>% round(3)`). This is perhaps surprising given the differences in level of confidence and the influence of safety on riding locations. However, the *distribution* of trips appears quite different by gender even if the mean number of trips is not. Whereas the distribution for men is roughly uniform, the distribution for women appears bimodal; women exceed men in both the 0-3 categories and the 13-20 categories (@fig-num-trips-gender). It appears as though women participating in this study are "all or nothing" cyclists; they either bike very little or quite a lot.

```{r}
#| label: fig-num-trips-gender
#| echo: true
#| eval: true
#| message: false
#| warning: false
#| fig-cap: "Number of trips per week"
#| code-fold: true
#| code-summary: "Show the code"

## get number of trips as a factor (for mann whitney u-test) and 
## numeric (for density plot)
df$number_of_trips_factor <- df$number_of_trips %>%
  as.factor()

levels(df$number_of_trips_factor) <- c("0-3", "4-7", "8-12", "13-20", "20+")
df$number_of_trips_num <- df$number_of_trips_factor %>%
  as.numeric()

df_num_trips <- df %>%
  group_by(gender) %>%
  count(number_of_trips_factor) %>%
  filter(gender %in% c("Female", "Male")) %>%
  na.omit(number_of_trips_factor) %>%
  mutate(Gender = gender)

ggplot(df_num_trips, aes(fill=Gender, y=n, x=number_of_trips_factor)) +
  geom_bar(position = "dodge",
           stat="identity",
           alpha = 0.5,
           color = "black") +
  scale_fill_manual(values = c(female_color, male_color)) +
  xlab("Number of trips") +
  ylab("Frequency")
```

```{r}
#| label: tbl-stat-results
#| tbl-cap: "Statistical test results"
#| echo: true
#| eval: true
#| message: false
#| warning: false
#| code-fold: true
#| code-summary: "Show the code"

stat_results <- list(
  c(
    topic = "Level of confidence in cycling by gender",
    test = "Mann Whitney U-test",
    p_value = conf_by_gender$p.value %>% round(3)
  ),
  c(
    topic = "Influence of safety on choice of riding locations by gender",
    test = "Mann Whitney U-test",
    p_value = infl_by_gender$p.value %>% round(3)
  ),
  c(
    topic = "Number of trips per week by gender",
    test = "Mann Whitney U-test",
    p_value = trips_by_gender$p.value %>% round(3)
  ),
  c(
  topic = "Number of unsafe points mapped by gender",
  test = "Mann Whitney U-test",
  p_value = num_pts_by_gender$p.value %>% round(3)
))

stat_results_df <- map_df(stat_results, ~as.data.frame(t(.))) %>%
  tibble

#knitr::kable(stat_results_df,
kbl(stat_results_df,
             col.names = c("Topic",
                           "Test",
                           "p-value"),
             label = NA, booktabs = TRUE)
```

## General spatial patterns of mapped unsafe locations

```{r}
#| label: reasons
#| echo: true
#| eval: true
#| message: false
#| warning: false

library(sf)
library(dplyr)
library(purrr)
library(magrittr)

pts_reasons <- pts %>% select(infrastructure,
                              traffic_proximity,
                              traffic_volume,
                              traffic_speed,
                              visibility,
                              pedestrians,
                              hills,
                              other.x) %>%
  st_set_geometry(NULL)

no_reasons_selected <- pts %>%
  filter(infrastructure == FALSE &
         traffic_proximity == FALSE &
         traffic_volume == FALSE &
         traffic_speed == FALSE &
         visibility == FALSE &
         pedestrians == FALSE &
         hills == FALSE &
         other.x == FALSE
         )

pts_reasons_sum <- pts_reasons %>%
  colSums() %>%
  data.frame() %>%
  mutate(reason = c("Lacking or poor infrastructure",
                    "Traffic proximity",
                    "Traffic volume",
                    "Traffic speed",
                    "Poor visibility from motorists",
                    "Potential conflicts with pedestrians",
                    "Steep hills",
                    "Other")) %>%
  `rownames<-`(NULL) %>%
  relocate("reason") %>%
  set_colnames(c("reason", "count")) %>%
  arrange(desc(count))
```

A few broad spatial patterns can be observed when examining the raw point data and the heat map (@fig-heat-map). It is apparent that many points are located near busy intersections, major transportation corridors (with the exception of interstate highways), commercial centers, and mixed-use areas of Eau Claire. Very few points appear in residential neighborhoods, reflecting the relatively high feelings of safety in these areas compared to others.

```{r}
#| label: fig-heat-map
#| echo: true
#| eval: true
#| message: false
#| warning: false
#| cache: false
#| fig-cap: "Raw data and heat map of unsafe points"
#| code-fold: true
#| code-summary: "Show the code"

library(leaflet)
library(sf)
library(leaflet.extras)

pts_df <- pts %>%
  st_set_geometry(NULL)
leaflet(pts) %>%
  addProviderTiles("CartoDB.DarkMatter") %>%
  addHeatmap(radius = 25, blur = 30, max = 1, intensity = 60, group = "Heat Map") %>%
  addCircleMarkers(lng = pts_df$x,
    lat = pts_df$y,
    fillOpacity = 0.3,
    color = "white",
    stroke = FALSE,
    radius = 5,
    group = "Individual points")  %>%
  addLayersControl(overlayGroups = c("Heat Map", "Individual points"), 
                   options = layersControlOptions(collapsed = FALSE)) %>%
  hideGroup("Individual points")
```

```{r}
#| label: grid-results
#| echo: true
#| eval: true
#| message: false
#| warning: false

grd <- st_read(here("data/ec_grid.geojson"),
               quiet = TRUE) %>%
  st_set_crs(4326)

neigh_count_df <- df$grd_id %>%
  table %>%
  data.frame %>%
  setNames(c("id", "user_count"))

neigh <- merge(grd, neigh_count_df, by = "id", all = TRUE) %>%
  replace_na(list(user_count=0))

tmap_mode("view")

user_count_by_neigh <- tm_shape(neigh) +
  tm_polygons(col = "user_count",
              palette = "YlGnBu",
              alpha = 0.8,
              title = "Number of respondents",
              id = "user_count",
              popup.vars = c("Respondents:" = "user_count"),
              group = "Number of respondents")

neigh$pt_count <- st_intersects(neigh, pts) %>% lengths

pt_count_by_neigh <- tm_shape(neigh) +
  tm_polygons(col = "pt_count",
              palette = "YlOrRd",
              alpha = 0.8,
              title = "Number of unsafe points",
              id = "pt_count",
              popup.vars = c("Number of points: " = "pt_count"),
              group = "Number of points")

pt_count_by_neigh_lf <- tmap_leaflet(pt_count_by_neigh)
user_count_by_neigh_lf <- tmap_leaflet(user_count_by_neigh)

cor_results <- cor(neigh$pt_count, neigh$user_count, method = "spearman")
```

In general, there is a high degree of correlation between the number of respondents per grid cell (as determined through self-identified home locations) and the number of unsafe points plotted ($\rho$ = `r cor_results %>% round(2)`; @fig-user-count and @fig-pt-count). This is unsurprising, since citizens are more likely to ride near their home. However, the spatial bias of respondents' home locations ought to be considered when making judgments about areas which are generally safe to ride. The unsafe locations identified in this study are certainly not exhaustive; these are locations which have a greater number of activity locations and are generally more accessible by bike. There are likely fewer points mapped on the outskirts of town not because these areas are safer but because the population is smaller there, and thus there are fewer cyclists. Additionally, cyclists who ride in areas with a dense concentration of unsafe points may indeed still feel safe most of the time by making minor route adjustments to avoid those precarious locations.

::::: fluid-row
::: col-md-6
```{r}
#| label: fig-user-count
#| echo: true
#| eval: true
#| message: false
#| warning: false
#| fig-cap: "User-identified home locations"
#| ##out.width = "320px"
#| code-fold: true
#| code-summary: "Show the code"

user_count_by_neigh_lf
```
:::

::: col-md-6
```{r}
#| label: fig-pt-count
#| echo: true
#| eval: true
#| message: false
#| warning: false
#| fig-cap: "Locations of unsafe points"
#| ##out.width = "320px"
#| code-fold: true
#| code-summary: "Show the code"

pt_count_by_neigh_lf
```
:::
:::::

Attached to each spatial response of unsafe locations is a set of reasons for why those locations are unsafe (@tbl-reasons). Despite the fact that for `r nrow(no_reasons_selected)` of the `r nrow(pts)` points no reasons were selected, the summaries are nevertheless informative since these are closely tied to the built environment. Of the options provided, "`r pts_reasons_sum[1,1]`" was identified as the most common reason followed by "`r pts_reasons_sum[2,1]`". This gives credence to the idea that cyclists do not feel safe around motor vehicles and that motor vehicles are the biggest deterrent to cyclists. This was followed by "`r pts_reasons_sum[3,1]`", indicating the importance of dedicated cycling infrastructure. "`r pts_reasons_sum[4,1]`" appears relatively often as the fourth most common reason for feeling unsafe, which is a bit unexpected given that cyclists are a greater threat to pedestrians than the other way around [@Graw2002]. Nevertheless, conflicts with pedestrians can lead to crashes.

```{r}
#| label: tbl-reasons
#| tbl-cap: "Reasons for feeling unsafe on a bicycle"
#| echo: true
#| eval: true
#| message: false
#| warning: false
#| code-fold: true
#| code-summary: "Show the code"

#knitr::kable(pts_reasons_sum,
kbl(pts_reasons_sum,
    booktabs = TRUE, linesep = c(""),
    col.names = c("Reason", "Count"),
    label = NA)
```

## Cluster analysis of mapped unsafe locations

```{r}
#| echo: true
#| eval: true
#| cache: false
#| message: false
#| warning: false

pts_3070 <- pts %>%
  st_transform(3070) %>%
  arrange(x)

remove_dups_within_dist <- function(pts_df, dist) {
  ## create empty holding tank for new point object, have to give it a crs
  new_pts <- st_sf(st_sfc()) %>%
    st_set_crs(st_crs(pts_df))

  ## create vector of rownames; will remove duplicated stuff from here
  pts_df$index <- 1:nrow(pts_df)

  ## create empty vector of duplicated indexes; will use this to skip over duplicates
  dup_indexes <- c()

  for (i in 1:nrow(pts_df)) {
    ## if the point's index has not been flagged as dup, don't skip over
    if (sum(dup_indexes %in% pts_df$index[i]) == 0) {
      tmp_pt <- pts_df[i,]

      ## put a buffer around it
      tmp_pt_buffer <- st_buffer(tmp_pt, dist)

      ## find points that intersect
      int_pts <- st_intersection(pts_df, tmp_pt_buffer)

      ## for all intersected points
      for (j in 1:nrow(int_pts)) {
        if (j == 1) {
          next
        } else {
          if (tmp_pt$user == int_pts$user[j]) {
            dup_indexes <- c(dup_indexes, int_pts$index[j])
          }
        }
      }
      new_pts <- rbind(new_pts, pts_df[i,])
    }
  }
  return(new_pts)
}

reduced_pts <- remove_dups_within_dist(pts_3070, 200)

clusters <- dbscan(reduced_pts %>% st_coordinates,
                   eps = 175,
                   minPts = 5)

reduced_pts$cluster <- clusters %>%
  pluck("cluster")

reduced_pts$cluster <- na_if(reduced_pts$cluster, 0)

cluster_pts_to_polygon <- function(pts, dist) {

  ## create placeholder for convex hull object
  c_hull <- st_sf(st_sfc()) %>%
    st_set_crs(st_crs(pts)) %>%
    st_as_sf() %>%
    mutate(cluster = NA)

  for (i in 1:length(na.omit(unique(pts$cluster)))) {

    ## filter by cluster number
    tmp_pts <- pts %>%
      filter(cluster == i)

    ## create convex hull object (returns geometry only)
    c_hull_geom_tmp <- st_convex_hull(st_union(tmp_pts))

    ## make in to sf object
    c_hull_sf_tmp <- st_as_sf(c_hull_geom_tmp)

    ## assign cluster number
    c_hull_sf_tmp$cluster <- i

    ## add to object
    c_hull <- rbind(c_hull, c_hull_sf_tmp)
  }

  ## buffer
  cluster_buff <- st_buffer(c_hull, dist)

  return(cluster_buff)
}

## use a small distance for cluster buffer
cluster_buff <- cluster_pts_to_polygon(reduced_pts, 20)

cluster_counts <- reduced_pts$cluster %>%
  table() %>%
  as.numeric()

cluster_buff$labels <- paste0(cluster_buff$cluster, " (n = ", cluster_counts, ")")
```

The DBSCAN algorithm is used to identify significant clusters of unsafe locations (@fig-cluster-web-map). However, inspections of the raw data revealed frequent occurrences of multiple points produced by a single user within a relatively small area, requiring some filtering before clustering. For example, around a few busy roundabouts (e.g., at the intersection of State St. and Patton St.) a single user produced several points at various places on the roundabout within distances of less than 50m. In theory, without any filtering, one individual could produce their own cluster, making such a location appear more significant than another cluster produced by many users who each mapped one point in the vicinity. So, multiple points produced by the same user within a distance of 200m were reduced to one. This resulted in a reduction of the total number of points from `r nrow(pts)` to `r nrow(reduced_pts)`. The authors use 5 minimum points and a search distance of 175m in creating clusters. These parameters were selected through a process of experimentation and was deemed to strike a nice balance in cluster size and number. What follows is commentary on the characteristics of each individual cluster.

```{r}
#| label: fig-cluster-web-map
#| echo: true
#| eval: true
#| cache: false
#| message: false
#| warning: false
#| fig-cap: "Clusters of points identified as unsafe for cycling using DBSCAN (_minPts_ = 5, _eps_ = 175m). Points produced by the same respondent within 200m are reduced to one."
#| code-fold: true
#| code-summary: "Show the code"

cluster_map <- tm_shape(cluster_buff) +
  tm_fill(col = "cluster",
          palette = "Set2",
          alpha = 0.8,
          title = "Cluster",
          labels = cluster_buff$labels,
          group = "Clusters") +
  tm_borders(lwd = 5,
             col = "black") +
  tm_shape(reduced_pts %>% mutate(as.factor(gender))) +
  tm_dots(col = "gender",
          title = "Gender",
          alpha = 0.5,
          palette = c(Female = female_color, Male = male_color, Other = other_color),
          group = "Unsafe points") +
  tm_layout(legend.just = "left")

## use tmap_leaflet object to get web map to appear as figure
cluster_map_leaflet <- tmap_leaflet(cluster_map)
cluster_map_leaflet
```

-   Cluster 1 (*n* = `r cluster_counts[1]`): *Intersection of N. Clairemont Ave. and Menomonie St.* -- this cluster lies at the confluence of a relatively busy intersection (seven lanes on one side of the street and four on the other side). Though there are crosswalks across each section of road, there is only one high-intensity activated crosswalk (HAWK) beacon (on the north side of Menomonie St.).

-   Cluster 2 (*n* = `r cluster_counts[2]`): *Water St., Summit Ave., and State St.* -- the largest cluster in the analysis by a good margin in terms of area and number of points, this cluster covers a mixed-use and commercial corridor near the University of Wisconsin - Eau Claire. Points are well-distributed across both Water St. and Summit Ave.; these two roads are one connected segment as the name changes on the bridge crossing the Chippewa River. Though Summit Ave. has a bicycle lane, at both ends of the bridge on this road, motorists must cross the bike lane in order to use the right turn lane. Two "sub-clusters" appear at intersections on State St. between Summit Ave. and Washington Ave.

-   Cluster 3 (*n* = `r cluster_counts[3]`): *Intersection of N. Clairemont Ave. and State Highway 37* -- this cluster lies at the confluence of a busy commercial corridor and several of the major medical facilities in Eau Claire. Unlike the intersection covered by Cluster 1, however, this intersection features four HAWK beacons. Users marked similar intersections to the East as unsafe, though these other intersections did not have enough points to form a cluster.

-   Cluster 4 (*n* = `r cluster_counts[4]`): *Intersection of Madison St. and Oxford Ave.* -- while there is now a bicycle underpass beneath Madison St., this area can still pose problems for cyclists needing to cross Oxford Ave. Further, one user marked the area just south of this intersection as unsafe -- at this point the Chippewa River Trail temporarily stops and empties into the road; those traveling south seeking the trail connection are forced onto the road.

-   Cluster 5 (*n* = `r cluster_counts[5]`): *Madison St. east of the Chippewa River* -- this is a section of road bounded by a large hill to the East and a relatively wide bridge to the West. Though there is a dedicated bicycle trail near this road, there are no bicycle lanes on Madison St. at this cluster.

-   Cluster 6 (*n* = `r cluster_counts[6]`): *Eau Claire Central Business District (CBD)* -- the second largest cluster in terms of area and number of points, this is a dense, mixed-use corridor covering the CBD and is similar in land use to Cluster 2. Points are well distributed across Farwell St., Barstow St., and Lake St. Lake St. contains a bike lane, but like on Summit Ave., right turning traffic must cross the bike lane both at the intersection of Lake St. and Barstow St. and at the intersection of Lake St. and Farwell St. The speed limit on Farwell St. is 30 mph but is 4-5 lanes with no bike lane. While traffic moves slower on Barstow St., the downtown core of Eau Claire, due to many stop signs, significant amounts of on-street parking can reduce visibility from motorists.

-   Cluster 7 (*n* = `r cluster_counts[7]`): *The Roundabout at State St. and Lexington Blvd.* -- this cluster lies at the southern end of a newly constructed -- and relatively complex -- roundabout at the top of a steep hill. Though there is a bicycle lane north of this roundabout, there is not one to the South, where most of the points are congregated.

-   Cluster 8 (*n* = `r cluster_counts[8]`): *Washington St. and Farwell St.* -- this cluster partially lies between Clusters 2 and 6, marking a transition zone between the historic Third Ward neighborhood and the downtown core of the city. A large "sub-cluster" of points appears at the intersection of Washington St. and Farwell St. The "sub-cluster" just to the Northeast lies at the base of a steep hill, and the road just to the East widens from two lanes to three.

In general, clusters can be found around intersections with heavy car traffic (clusters 1, 3, 4, 5, 7, and 8) and in mixed use areas where cars are also common (clusters 2 and 6). It is telling that unsafe points are marked at wide intersections -- such as clusters 1 and 3 along Clairemont Ave. -- as this indicates that despite the apparent impenetrability of wide thoroughfares and the lack of any cycling-based infrastructure, cyclists are nevertheless riding in these locations. The four southernmost clusters (clusters 1-3 and 7) are also notably located in a ring surrounding the local university campus. Despite the high amount of survey distribution in this area -- which obviously impacts results -- it should be noted that a reasonable share of students does not own or use a car yet still need to commute in and around this area for a variety of trip purposes. Further, all clusters show a reasonable mix of points produced by women and men, with the exception of Cluster 7, which is made up of points produced exclusively by men. This warrants inspection of gender-based clusters.

## Gendered spatial patterns of mapped unsafe locations

```{r}
#| label: fig-gender-cluster-web-map
#| echo: true
#| eval: true
#| cache: false
#| message: false
#| warning: false
#| fig-cap: "Clusters of points identified as unsafe for cycling by gender using DBSCAN (_minPts_ = 4, _eps_ = 200m); Points produced by the same respondent within 200m are reduced to one."
#| code-fold: true
#| code-summary: "Show the code"

eps_gender <- 200
min_pts_gender <- 4

## female only
reduced_pts_female <- reduced_pts %>% filter(gender == "Female")
clusters_female <- dbscan(reduced_pts_female %>% st_coordinates,
                          eps = eps_gender,
                          minPts = min_pts_gender)
reduced_pts_female$cluster <- clusters_female %>%
  pluck("cluster")

reduced_pts_female$cluster <- na_if(reduced_pts_female$cluster, 0)

cluster_buff_female <- cluster_pts_to_polygon(reduced_pts_female, 20)

cluster_counts_female <- reduced_pts_female$cluster %>%
  table() %>%
  as.numeric()

cluster_buff_female$labels <- paste0(cluster_buff_female$cluster,
                                     " (n = ",
                                     cluster_counts_female,
                                     ")")


## male only
reduced_pts_male <- reduced_pts %>% filter(gender == "Male")
clusters_male <- dbscan(reduced_pts_male %>% st_coordinates,
                        eps = eps_gender,
                        minPts = min_pts_gender)
reduced_pts_male$cluster <- clusters_male %>%
  pluck("cluster")

reduced_pts_male$cluster <- na_if(reduced_pts_male$cluster, 0)

cluster_buff_male <- cluster_pts_to_polygon(reduced_pts_male, 20)

cluster_counts_male <- reduced_pts_male$cluster %>%
  table()%>%
  as.numeric()

cluster_buff_male$labels <- paste0(cluster_buff_male$cluster,
                                   " (n = ",
                                   cluster_counts_male,
                                   ")")

gender_cluster_map <- tm_shape(cluster_buff_female) +
  tm_fill(col = "cluster",
          palette = female_color,
          alpha = 0.5,
          title = "Female clusters",
          labels = cluster_buff_female$labels,
          group = "Female clusters") +
  tm_borders(lwd = 5,
             col = "black") +
    tm_shape(cluster_buff_male) +
    tm_fill(col = "cluster",
            palette = male_color,
            alpha = 0.5,
            title = "Male clusters",
            labels = cluster_buff_male$labels,
            group = "Male clusters") +
    tm_borders(lwd = 5,
               col = "black") +
  tm_shape(reduced_pts %>% mutate(as.factor(gender))) +
  tm_dots(col = "gender",
          title = "Gender",
          alpha = 0.5,
          palette = c(Female = female_color, Male = male_color, Other = other_color),
          group = "Unsafe points") +
  tm_layout(legend.just = "left")

gender_cluster_map_center <- cluster_buff_male %>%
  st_union() %>%
  st_centroid() %>%
  st_transform(4326)

gender_cluster_map_center$lng <- gender_cluster_map_center %>%
 st_coordinates() %>%
 data.frame() %>%
 pull(X)

gender_cluster_map_center$lat <- gender_cluster_map_center %>%
 st_coordinates() %>%
 data.frame() %>%
 pull(Y)

gender_cluster_map_leaflet <- tmap_leaflet(gender_cluster_map)
gender_cluster_map_leaflet %>%
  setView(zoom = 14, lng = gender_cluster_map_center$lng, lat = gender_cluster_map_center$lat)
```

Gender-based clusters use slightly modified DBSCAN parameters -- four minimum points and a search distance of 200m -- to account for the fewer data points available for clustering as a result of grouping by gender (@fig-gender-cluster-web-map). Clusters for both women and men are generally located toward the center of study area with clusters for both genders located around the mixed-use areas of Eau Claire. However, there are only three clusters created for women and seven for men. Keeping the original parameters results in an even starker picture with one cluster for women and seven for men. The clusters for men are also larger in terms of area, and they extend farther from the city center.

Investigating all points of unsafe locations by gender reveals several intriguing trends (@fig-points-by-gender). The outskirts of the city are dominated by points produced by men. At first glance, it would appear as though a single "power user" may have produced all of these points, which would perhaps warrant their removal from analysis. However, inspection of individual data points demonstrates that each of the points placed farthest north, east, south, and west were indeed produced by four unique users. As a result, all are worth keeping, and the convex hulls created by gender are thus highly disparate in terms of area.

```{r}
#| label: fig-points-by-gender
#| echo: true
#| eval: true
#| message: false
#| warning: false
#| fig-cap: "Locations identified as unsafe for cycling by gender"
#| code-fold: true
#| code-summary: "Show the code"

pts_female <- pts %>% filter(gender == "Female")
pts_male <- pts %>% filter(gender == "Male")
pts_other <- pts %>% filter(gender == "Other")

gender_map <- leaflet() %>%
  addProviderTiles("CartoDB.Positron") %>%
  addCircleMarkers(lng = pts_female$x,
                   lat = pts_female$y,
                   radius = 4,
                   stroke = TRUE,
                   color = "black",
                   weight = .5,
                   opacity = 1,
                   fill = TRUE,
                   fillColor = female_color,
                   fillOpacity = 0.6) %>%
  addCircleMarkers(lng = pts_male$x,
                   lat = pts_male$y,
                   radius = 4,
                   stroke = TRUE,
                   color = "black",
                   weight = .5,
                   opacity = 1,
                   fill = TRUE,
                   fillColor = male_color,
                   fillOpacity = 0.6) %>%
  addCircleMarkers(lng = pts_other$x,
                   lat = pts_other$y,
                   radius = 4,
                   stroke = TRUE,
                   color = "black",
                   weight = .5,
                   opacity = 1,
                   fill = TRUE,
                   fillColor = other_color,
                   fillOpacity = 0.6) %>%
  addLegend("bottomright",
            colors = c(female_color,
                       male_color,
                       other_color),
            labels = c("Female",
                       "Male",
                       "Other"),
            opacity = 1)

gender_map
```

```{r}
#| label: fig-convex-hull
#| echo: true
#| eval: true
#| message: false
#| warning: false
#| cache: false
#| fig-cap: "Convex hull of responses by gender"

## convex hull female
ch_f <- st_union(pts_female) %>%
  st_convex_hull %>%
  st_as_sf %>%
  mutate(info = "Female convex hull",
         gender = "female")

## convex hull male
ch_m <- st_union(pts_male) %>%
  st_convex_hull %>%
  st_as_sf %>%
  mutate(info = "Male convex hull",
         gender = "male")

ch_f$area <- ch_f %>%
  st_area %>%
  set_units("km^2") %>%
  as.numeric %>%
  round(0)

ch_m$area <- ch_m %>%
  st_area %>%
  set_units("km^2") %>%
  as.numeric %>%
  round(0)
```

The convex hull for women is almost completely encompassed by the convex hull for men and is about a fourth of the area (@fig-convex-hull-map). Specifically, the areas for women and men are `r ch_f$area` km<sup>2</sup> vs. `r ch_m$area` km<sup>2</sup>, respectively. While the survey in this study did not ask about mobility and cycling extent per se, due to the way the survey question was framed -- pertaining to feelings of being unsafe *where* respondents actually ride -- this result may be indicative of gendered differences in mobility. Put more plainly, the cycling infrastructure in Eau Claire, notwithstanding broader cultural factors, may offer more locational freedom to men. While future research could confirm or deny this hypothesis, it is in line with broader research on mobility in the United States.

```{r}
#| label: fig-convex-hull-map
#| echo: true
#| eval: true
#| message: false
#| warning: false
#| cache: false
#| fig-cap: "Convex hull of reponses by gender"
#| code-fold: true
#| code-summary: "Show the code"

pts$user_short <- str_sub(pts$user, start = -3) %>%
  toupper()
pts$info <- "Unsafe location (click for detailed data)"

chull_map <- tm_shape(ch_m) +
  tm_fill(col = male_color,
          alpha = 0.5,
          popup.vars = FALSE,
          id = "info",
          group = "Convex hull (male)") +
  tm_shape(ch_f) +
  tm_fill(alpha = 0.5,
          col = female_color,
          popup.vars = FALSE,
          id = "info",
          group = "Convex hull (female)") +
  tm_shape(pts) +
  tm_dots(col = NA,
          id = "info",
          palette = c("#fffdfb"),
          legend.show = FALSE,
          popup.vars = c("Gender: " = "gender",
                         "Age: " = "age",
                         "Helmet usage: " = "helmet",
                         "User id: " = "user_short"
                         ),
          size = 0.075,
          alpha = 0.8,
          group = "Unsafe points") +
  tm_view(set.view = 12)

chull_map_leaflet <- tmap_leaflet(chull_map)
chull_map_leaflet %>%
  setView(zoom = 11, lng = mean(pts$x), lat = mean(pts$y))
```

# Discussion, Limitations, and Future Work

The results of this study are consistent with previous literature on cycling perception in some ways but markedly different in others. Women and men are significantly different in terms of overall cycling confidence and how concerns of safety influence riding locations. While this study did not ask participants open-ended questions about perception, other works suggest that inadequate infrastructure is shown to have greater influence on the cycling rates of women than men [@Manton2016; @Misra2018; @Hood2013].

The convex hulls revealed in this study are emblematic of the general trends in gender cycling behavior. The spatial extent of where men mapped points -- and thus, likely where they ride more generally -- exceeds the extent of points mapped by women, at least at the extremes. Individuals who feel more unsafe cycling are less likely to travel farther distances. Other research indeed confirms that men are more likely to travel further when cycling [@Misra2018]. All this said, it is notable that even though perceptions of safety and confidence differ, there is not a significant difference in the number of trips taken per week by gender.

It follows from this that despite the fact that women have more negative perceptions about cycling, it does not appear to reduce their number of trips. Though cycling is largely dominated by men in the United States currently, this finding of relative parity in terms of the number of trips is a departure from other studies in this country. This finding suggests a desire of women to participate in cycling which should encourage policy makers to not consider it purely an activity for men. With the political will to do so, the creation of a safe cycling environment is attainable -- as demonstrated in other countries [@Pucher2008] -- which can lead to greater gender equity.

Even though there is a greater concentration of points near the city center, it is notable that points are indeed scattered throughout the city, even at the city's edges. While these peripheral locations have little dedicated cycling infrastructure -- and, to the casual observer, would not be utilized by bicycle at all -- the presence of points indicate cycling relevance. Cyclists are still riding in these locations and may desire to ride there more but presently feel unsafe doing so.

In addition to the analysis of unsafe points as a whole, the analysis of the clusters reveals several common themes. Clusters are generally located in commercial and mixed-use areas rather than quiet residential neighborhoods. While respondents perceive mixed-use areas as more unsafe, this does not necessarily mean that mixed-use areas are detrimental to commuter cycling in general. In fact, the converse has been demonstrated other cases, both within [@Hull2014] and outside of the United States [@Cervero1996]. In this study however, this result is likely the product of car dependency creating traffic in commercial and mixed-use areas, leading to a greater potential for conflict between cyclists and motor vehicles.

Unsurprisingly, many of the clusters are located at intersections: spaces where cyclists are likely to encounter vehicular traffic. This is further corroborated by the top two cited reasons for feeling unsafe being related to traffic and aligns with other literature [@Wang2018; @Digiola2017]. Bridges also appear to be a common site for clusters, yet it is unclear if these can be explained purely by the cyclists being forced into close proximity with vehicles, or if the structural elements of the bridges themselves create relative feelings of being unsafe. Additionally, places where motor vehicles must cross a bike lane are common locations perceived to be unsafe.

There are several limitations to this study that cannot be ignored. First, the study did not utilize random sampling, as this would be difficult to achieve given the target population. Additionally, since fliers were distributed in late summer 2021, the results cannot be applied to cycling in the winter months. Indeed, the significant amount of snowfall combined with an inadequate handling of snow in bike lanes and trails make the study inapplicable to winter cycling. The number of respondents was also relatively small ($n$ = 99), and the survey did not include an exhaustive list of all reasons why cyclists may feel unsafe; fear of crime, for instance was not included. Additionally, a study such as this does rely on respondents' capability of accurately placing locations on a map. Though web maps are increasingly utilized by the general population, this capacity is at times less than perfect. Finally, the city of Eau Claire is largely white, and the lack of responses from people of color is a significant disadvantage to a study concerned with equity. Future work could deliver a similar survey in other municipalities, perhaps ones which are more diverse, to include the voices of historically marginalized populations.

Future work could also compare the locations of where respondents feel unsafe with where crashes have actually happened. While it would be expected that the two would have a strong correlation, differences may be illuminating. Moreover, it would be telling to compare the locations where respondents feel unsafe with land use data and characteristics of the built environment: street width; slope; and the presence or absence of traffic signals, bicycle lanes, and intersections. In addition to these possibilities for study expansion, the data collected in this study possesses many variables and relationships which remain to be studied. These include differences in the reasons *why* locations were identified as unsafe for cycling by demographic groups, differences in convex hulls by demographic groups other than gender, and other age/race related comparisons.

# Conclusion

This study aimed to investigate both the spatial and non-spatial patterns in perceived cycling safety in Eau Claire, Wisconsin. To accomplish this, the authors created a survey instrument for identifying locations perceived to be unsafe for cycling and conducted a survey of local residents. The survey observations were then analyzed for statistical differences in cycling ridership through Mann-Whitney $U$-tests, demonstrated where infrastructure improvements could be focused through cluster analysis, and compared the spatial distribution of ridership points through convex hulls.

While a growing body of literature has investigated cycling safety perceptions, three aspects of this study are particularly unique. First, the authors implemented an interactive open-source web application to collect public survey responses. Second, the study used spatial analysis on where respondents feel unsafe, rather than simply where cyclists ride, or what non-spatial infrastructure characteristics are undesirable for cycling. Third, this study is the first, to the authors' knowledge, that analyzed the gendered spatial patterns in cycling safety perceptions.

The study findings align with previous literature on cycling safety perception in some aspects but diverge in others. Gender differences in overall cycling confidence and safety concerns' impact on riding locations are consistent with previous work, however, while men tend to exhibit greater spatial extent in cycling patterns compared to women, there's no significant gender gap in the number of weekly trips. Despite women's more negative perceptions, their trip frequency remains comparable, challenging the notion of cycling as solely male-dominated in the US. This suggests a desire for gender-inclusive cycling environments, emphasizing the need for policymakers to prioritize safety infrastructure. While unsafe points are clustered in areas with mixed land use and intersections, it's important to recognize that these locations remain relevant for cycling, albeit hindered by traffic-related safety concerns.

Some results are quite encouraging, such as the relative parity in the number of trips taken by gender, but significant progress is still needed to make cycling more equitable. Public policy and infrastructure design have indeed been successful in creating urban areas that are safer for cycling. These can be used to calm traffic, improve public transport integration, support bike sharing programs, and promote cycling through promotional events [@Pucher2011]. These techniques can make cycling safer, and as suggested in this study, perhaps more equitable as well. Such transportation improvements produce tangible community benefits which deserve consideration from planners and public officials.

# Acknowledgments

This research was funded by the Office of Research and Sponsored Programs at the University of Wisconsin - Eau Claire. The authors would like to thank the survey participants for contributing the data which made this project possible.

# References

```{r}
#| label: bib
#| echo: false
#PrintBibliography(bib)
```
