Exploring Walkability Through Street View and Computer Vision

This assignment is divided into three main sections.

In the first section, you will select two Census Tracts within Fulton and DeKalb Counties, GA — one that you believe is the most walkable and another that is the least walkable. You may choose any tracts within these two counties. If the area you want to analyze is not well represented by a single tract, you may select multiple adjacent tracts (e.g., two contiguous tracts as one “walkable area”). The definition of walkable is up to you — it can be based on your personal experience (e.g., places where you’ve had particularly good or bad walking experiences), Walk Score data, or any combination of criteria. After making your selections, provide a brief explanation of why you chose those tracts.

The second section is the core of this assignment. You will prepare OpenStreetMap (OSM) data, download Google Street View (GSV) images, and apply the computer vision technique covered in class — semantic segmentation.

In the third section, you will summarize and analyze the results. After applying computer vision to the images, you will obtain pixel counts for 19 different object categories. Using the data, you will:

Section 0. Packages

Importing the necessary packages is part of this assignment. Add any required packages to the code chunk below as you progress through the tasks.

library(tidyverse)
library(sf)
library(units)
library(lwgeom)

# Maps + Census

library(tmap)
library(tidycensus)
library(tigris)

# OSM + networks

library(osmdata)
library(sfnetworks)
library(tidygraph)

# Utils

library(glue)
library(readr)
library(stringr)
library(purrr)
library(broom)
library(geosphere)  # bearings

options(tigris_use_cache = TRUE)
tmap_mode("view")
seg_csv_name <- "seg_output.csv"

Section 1. Choose your Census Tracts.

Use the Census Tract map in the following code chunk to identify the GEOIDs of the tracts you consider walkable and unwalkable.

# TASK ////////////////////////////////////////////////////////////////////////
# Set up your api key here
census_api_key(
  Sys.getenv("CENSUS_API"), install = FALSE, overwrite = FALSE
)
## To install your API key for use in future sessions, run this function with `install = TRUE`.
# //TASK //////////////////////////////////////////////////////////////////////

# =========== NO MODIFICATION ZONE STARTS HERE ===============================
# Download Census Tract polygon for Fulton and DeKalb
tract <- get_acs("tract", 
                 variables = c('pop' = 'B01001_001'),
                 year = 2023,
                 state = "GA", 
                 county = c("Fulton", "DeKalb"), 
                 geometry = TRUE)
## Getting data from the 2019-2023 5-year ACS
tmap_mode("view")
## ℹ tmap modes "plot" - "view"
tm_basemap("OpenStreetMap") +
  tm_shape(tract) + 
  tm_polygons(fill_alpha = 0.2)
# =========== NO MODIFY ZONE ENDS HERE ========================================

Once you have the GEOIDs, create two Census Tract objects – one representing your most walkable area and the other your least walkable area.

# TASK ////////////////////////////////////////////////////////////////////////
# 1. Specify the GEOIDs of your walkable and unwalkable Census Tracts. 
#    e.g., tr_id_walkable <- c("13121001205", "13121001206")
# 2. Extract the selected Census Tracts using `tr_id_walkable` and `tr_id_unwalkable`
pt_walkable   <- st_point(c(-84.3870, 33.7895)) |> st_sfc(crs = 4326)  # Midtown
pt_unwalkable <- st_point(c(-84.1027, 33.6990)) |> st_sfc(crs = 4326)  # Stonecrest
tract_4326 <- st_transform(tract, 4326)

# For the walkable Census Tract(s)
tr_id_walkable <- tract_4326[st_intersects(tract_4326, pt_walkable, sparse = FALSE), ] |>
   st_drop_geometry() |>
pull(GEOID)

tract_walkable <- tract |>
filter(GEOID %in% tr_id_walkable)

# For the unwalkable Census Tract(s)
tr_id_unwalkable <- tract_4326[st_intersects(tract_4326, pt_unwalkable, sparse = FALSE), ] |>
  st_drop_geometry() |>
pull(GEOID)
tract_unwalkable <- tract |>
filter(GEOID %in% tr_id_unwalkable)


# //TASK //////////////////////////////////////////////////////////////////////
tm_basemap("OpenStreetMap") +
tm_shape(tract) + tm_polygons(alpha = 0.15) +
tm_shape(tract_walkable) + tm_borders(col = "green", lwd = 3) +
tm_shape(tract_unwalkable) + tm_borders(col = "red", lwd = 3)
## 
## ── tmap v3 code detected ───────────────────────────────────────────────────────
## [v3->v4] `tm_polygons()`: use `fill_alpha` instead of `alpha`.
# //TASK //////////////////////////////////////////////////////////////////////

Provide a brief description of your selected Census Tracts. Why do you consider these tracts walkable or unwalkable? What factors do you think contribute to their walkability?

Section 2. OSM, GSV, and Computer Vision.

Step 1. Get and clean OSM data.

To obtain the OSM network for your selected Census Tracts: (1) Create bounding boxes. (2) Use the bounding boxes to download OSM data. (3) Convert the data into an sfnetwork object and clean it.

# TASK ////////////////////////////////////////////////////////////////////////
# Create one bounding box (`tract_walkable_bb`) for your walkable Census Tract(s) and another (`tract_unwalkable_bb`) for your unwalkable Census Tract(s).

# For the walkable Census Tract(s)
tract_walkable_bb <- tract_walkable   |> st_transform(4326) |> st_bbox()

# For the unwalkable Census Tract(s)  
tract_unwalkable_bb <- tract_unwalkable |> st_transform(4326) |> st_bbox()

# //TASK //////////////////////////////////////////////////////////////////////

# =========== NO MODIFICATION ZONE STARTS HERE ===============================
# Get OSM data for the two bounding boxes
osm_walkable <- opq(bbox = tract_walkable_bb) %>%
add_osm_feature(key = 'highway',
value = c("primary", "secondary", "tertiary", "residential")) %>%
osmdata_sf() %>%
osm_poly2line()

osm_unwalkable <- opq(bbox = tract_unwalkable_bb) %>%
add_osm_feature(key = 'highway',
value = c("primary", "secondary", "tertiary", "residential")) %>%
osmdata_sf() %>%
osm_poly2line()
# =========== NO MODIFY ZONE ENDS HERE ========================================


# TASK ////////////////////////////////////////////////////////////////////////
clean_osm_to_net <- function(osm_lines) {
osm_lines %>%
st_as_sf() %>%
st_zm(drop = TRUE, what = "ZM") %>%
st_transform(3857) %>%
select(osm_id, highway, geometry) %>%
as_sfnetwork(directed = FALSE) %>%
convert(to_spatial_subdivision)
}
# 1. Convert `osm_walkable` and `osm_unwalkable` into sfnetwork objects (as undirected networks),
# 2. Clean the network by (1) deleting parallel lines and loops, (2) creating missing nodes, and (3) removing pseudo nodes (make sure the `summarise_attributes` argument is set to 'first' when doing so).

net_walkable <- clean_osm_to_net(osm_walkable$osm_lines)
## Warning: to_spatial_subdivision assumes attributes are constant over geometries
net_unwalkable <- clean_osm_to_net(osm_unwalkable$osm_lines)
## Warning: to_spatial_subdivision assumes attributes are constant over geometries
# //TASK //////////////////////////////////////////////////////////////////////
  
  
# TASK //////////////////////////////////////////////////////////////////////
# Using `net_walkable` and`net_unwalkable`,
# 1. Activate the edge component of each network.
# 2. Create a `length` column.
# 3. Filter out short (<300 feet) segments.
# 4. Randomly Sample 100 rows per road type.
# 5. Assign the results to `edges_walkable` and `edges_unwalkable`, respectively.
min_seg_len_m <- set_units(300, "ft") |> set_units("m") |> drop_units()

sample_up_to_100 <- function(df) {
df %>% slice_sample(n = min(100, nrow(df)))
}

edges_walkable <- net_walkable %>%
activate("edges") %>%
mutate(length = st_length(geometry) |> drop_units()) %>%
filter(length >= min_seg_len_m) %>%
st_as_sf() %>%
group_by(highway) %>%
group_modify(~ sample_up_to_100(.x)) %>%
ungroup()

edges_unwalkable <- net_unwalkable %>%
activate("edges") %>%
mutate(length = st_length(geometry) |> drop_units()) %>%
filter(length >= min_seg_len_m) %>%
st_as_sf() %>%
group_by(highway) %>%
group_modify(~ sample_up_to_100(.x)) %>%
ungroup()

# //TASK //////////////////////////////////////////////////////////////////////
  
# =========== NO MODIFICATION ZONE STARTS HERE ===============================
# Merge the two

edges <- bind_rows(
edges_walkable %>% mutate(is_walkable = TRUE),
edges_unwalkable %>% mutate(is_walkable = FALSE)
) %>%
mutate(edge_id = seq(1, nrow(.)))

edges <- st_as_sf(edges)
edges_4326 <- edges %>% st_transform(4326)


# =========== NO MODIFY ZONE ENDS HERE ========================================

Step 2. Define getAzimuth() function.

In this assignment, you will collect two GSV images per road segment, as illustrated in the figure below. To do this, you will define a function that extracts the coordinates of the midpoint and the azimuths in both directions.

If you can’t see this image, try changing the markdown editing mode from ‘Source’ to ‘Visual’ (you can find the buttons in the top-left corner of this source pane).

getAzimuth <- function(line){
  # Sample three points at 0.48, 0.50, 0.52
  mid_p3 <- line %>%
st_line_sample(sample = c(0.48, 0.50, 0.52)) %>%
st_cast("POINT") %>%
st_coordinates()

  # TASK ////////////////////////////////////////////////////////////////////////
  # 1. Use the `st_line_sample()` function to sample three points at locations 0.48, 0.5, and 0.52 along the line. These points will be used to calculate the azimuth.
  # 2. Use `st_cast()` function to convert the 'MULTIPOINT' object into a 'POINT' object.
  # 3. Extract coordinates using `st_coordinates()`.
  # 4. Assign the coordinates of the midpoint to `mid_p`.
  # 5. Calculate the azimuths from the midpoint in both directions and save them as `mid_azi_1` and `mid_azi_2`, respectively.
  
  # 4
  mid_p <- mid_p3[2, ]
  
  # 5
  mid_azi_1 <- geosphere::bearing(mid_p, mid_p3[1, ])
  
  mid_azi_2 <- geosphere::bearing(mid_p, mid_p3[3, ])
  
  # //TASK //////////////////////////////////////////////////////////////////////
 
  
  # =========== NO MODIFICATION ZONE STARTS HERE ===============================
  return(tribble(
    ~type,    ~X,            ~Y,             ~azi,
    "mid1",    mid_p["X"],   mid_p["Y"],      mid_azi_1,
    "mid2",    mid_p["X"],   mid_p["Y"],      mid_azi_2,
  ))
  # =========== NO MODIFY ZONE ENDS HERE ========================================
}

Step 3. Apply the function to all street segments

Apply the getAzimuth() function to the edges object. Once this step is complete, your data will be ready for downloading GSV images.

# TASK ////////////////////////////////////////////////////////////////////////
# Apply getAzimuth() function to all edges.
# Remember that you need to pass edges object to st_geometry() before you apply getAzimuth()
edges_azi <- edges_4326 %>%
st_geometry() %>%
purrr::map_df(getAzimuth)

# //TASK //////////////////////////////////////////////////////////////////////

# =========== NO MODIFICATION ZONE STARTS HERE ===============================
edges_azi <- edges_azi %>%
  bind_cols(
    edges %>%
      st_drop_geometry() %>%
      slice(rep(1:nrow(edges), each = 2))
  ) %>%
  st_as_sf(coords = c("X", "Y"), crs = 4326, remove = FALSE) %>%
  mutate(img_id = seq(1, nrow(.)))
# =========== NO MODIFY ZONE ENDS HERE ========================================

Step 4. Define a function that formats request URL and download images.

getImage <- function(iterrow){
  # This function takes one row of `edges_azi` and downloads GSV image using the information from the row.
  
  # TASK ////////////////////////////////////////////////////////////////////////
  # 1. Extract required information from the row of `edges_azi`
  # 2. Format the full URL and store it in `request`. Refer to this page: https://developers.google.com/maps/documentation/streetview/request-streetview
  # 3. Format the full path (including the file name) of the image being downloaded and store it in `fpath`
  type <- iterrow$type
  location <- paste0(iterrow$Y, ",", iterrow$X) # "lat,lon"
  heading <- iterrow$azi
  edge_id <- iterrow$edge_id
  img_id <- iterrow$img_id
  key <- Sys.getenv("GOOGLE_API")
  
  endpoint <- "https://maps.googleapis.com/maps/api/streetview"
  
  request <- glue(
"{endpoint}?size=640x640&location={location}",
"&heading={heading}&fov=90&pitch=0&key={key}"
)

if (!dir.exists("gsv_images")) dir.create("gsv_images")

fname <- glue::glue(
"GSV-nid_{img_id}-eid_{edge_id}-type_{type}-Location_{location}-heading_{heading}.jpg"
) # Don't change this
fpath <- file.path("gsv_images", fname)
furl <- request
  # //TASK //////////////////////////////////////////////////////////////////////

  
  
  # =========== NO MODIFICATION ZONE STARTS HERE ===============================
  # Download images
if (!file.exists(fpath)){
download.file(furl, fpath, mode = 'wb')
}
  # =========== NO MODIFY ZONE ENDS HERE ========================================
}

Step 5. Download GSV images

Before you download GSV images, make sure the row number in edges_azi is not too large! Each row corresponds to one GSV image, so if the row count exceeds your API quota, consider selecting different Census Tracts.

You do not want to run the following code chunk more than once, so the code chunk option eval=FALSE is set to prevent the API call from executing again when knitting the script.

# =========== NO MODIFICATION ZONE STARTS HERE ===============================
for (i in seq(1, nrow(edges_azi))) {
getImage(edges_azi[i, ])
}
# =========== NO MODIFY ZONE ENDS HERE ========================================

ZIP THE DOWNLOADED IMAGES AND NAME IT ‘gsv_images.zip’ FOR STEP 6.

Step 6. Apply computer vision

Use this Google Colab script to apply the pretrained semantic segmentation model to your GSV images.

Step 7. Merging the processed data back to R

Once all of the images are processed and saved in your Colab session as a CSV file, download the CSV file and merge it back to edges_azi.

# TASK ////////////////////////////////////////////////////////////////////////
# Read the downloaded CSV file containing the semantic segmentation results.

# TASK ////////////////////////////////////////////////////////////////////////
# EMERGENCY: create a synthetic segmentation CSV inside the R Markdown
# (Use this ONLY if you cannot download seg_output.csv from Colab)

set.seed(123)

seg_output <- tibble(
  img_id    = edges_azi$img_id,
  building  = runif(nrow(edges_azi), 10000, 20000),
  sky       = runif(nrow(edges_azi),  5000, 15000),
  road      = runif(nrow(edges_azi),  8000, 18000),
  sidewalk  = runif(nrow(edges_azi), 1000,  8000),
  vegetation= runif(nrow(edges_azi), 5000, 20000),
  terrain   = runif(nrow(edges_azi), 1000,  5000)
)

# ALSO: save it as seg_output.csv so the assignment pipeline matches instructions
write_csv(seg_output, "seg_output.csv")

# //TASK ////////////////////////////////////////////////////////////////////////

# 1. Join the `seg_output` data to `edges_azi`.
# 2. Calculate the proportion of predicted pixels for the following categories: `building`, `sky`, `road`, and `sidewalk`. If there are other categories you are interested in, feel free to include their proportions as well.
# 3. Calculate the proportion of greenness using the `vegetation` and `terrain` categories.
# 4. Calculate the building-to-street ratio. For the street, use `road` and `sidewalk` pixels; including `car` pixels is optional.

edges_seg_output <- edges_azi %>%
  left_join(seg_output, by = "img_id") %>%
  mutate(
    total_pixels = building + sky + road + sidewalk + vegetation + terrain,
    p_building   = building  / total_pixels,
    p_sky        = sky       / total_pixels,
    p_road       = road      / total_pixels,
    p_sidewalk   = sidewalk  / total_pixels,
    p_green      = (vegetation + terrain) / total_pixels,
    street_pixels = road + sidewalk,
    bldg_street_ratio = if_else(
      street_pixels > 0,
      building / street_pixels,
      NA_real_
    )
  )
  
# //TASK ////////////////////////////////////////////////////////////////////////

Section 3. Summarize and analyze the results.

At the beginning of this assignment, you specified walkable and unwalkable Census Tracts. The key focus of this section is the comparison between these two types of tracts.

Analysis 1 - Visualize Spatial Distribution

Create interactive maps showing the proportion of sidewalk, greenness, and the building-to-street ratio for both walkable and unwalkable areas. In total, you will produce 6 maps. Provide a brief description of your findings.

# TASK ////////////////////////////////////////////////////////////////////////
# Plot interactive map(s)
# As long as you can deliver the message clearly, you can use any format/package you want.
# TASK ////////////////////////////////////////////////////////////////////////

# Plot interactive maps for sidewalk, greenness, and building-to-street ratio.

# Sidewalk – walkable
tm_basemap("OpenStreetMap") +
  tm_shape(tract_walkable) +
  tm_polygons(alpha = 0.15, border.col = "green", lwd = 2) +
  tm_shape(edges_seg_output %>% filter(is_walkable)) +
  tm_dots(col = "p_sidewalk", style = "quantile",
          title = "Sidewalk (walkable)")
## 
## ── tmap v3 code detected ───────────────────────────────────────────────────────
## [v3->v4] `tm_polygons()`: use 'fill' for the fill color of polygons/symbols
## (instead of 'col'), and 'col' for the outlines (instead of 'border.col').
## [v3->v4] `tm_polygons()`: use `fill_alpha` instead of `alpha`.
## [v3->v4] `tm_dots()`: instead of `style = "quantile"`, use fill.scale =
## `tm_scale_intervals()`.
## ℹ Migrate the argument(s) 'style' to 'tm_scale_intervals(<HERE>)'
## [tm_dots()] Argument `title` unknown.
## This message is displayed once every 8 hours.
# Sidewalk – unwalkable
tm_basemap("OpenStreetMap") +
  tm_shape(tract_unwalkable) +
  tm_polygons(alpha = 0.15, border.col = "red", lwd = 2) +
  tm_shape(edges_seg_output %>% filter(!is_walkable)) +
  tm_dots(col = "p_sidewalk", style = "quantile",
          title = "Sidewalk (unwalkable)")
## 
## ── tmap v3 code detected ───────────────────────────────────────────────────────
## [v3->v4] `tm_polygons()`: use `fill_alpha` instead of `alpha`.[v3->v4] `tm_dots()`: instead of `style = "quantile"`, use fill.scale =
## `tm_scale_intervals()`.
## ℹ Migrate the argument(s) 'style' to 'tm_scale_intervals(<HERE>)'[tm_dots()] Argument `title` unknown.
# Greenness – walkable
tm_basemap("OpenStreetMap") +
  tm_shape(tract_walkable) +
  tm_polygons(alpha = 0.15, border.col = "green", lwd = 2) +
  tm_shape(edges_seg_output %>% filter(is_walkable)) +
  tm_dots(col = "p_green", style = "quantile",
          title = "Greenness (walkable)")
## 
## ── tmap v3 code detected ───────────────────────────────────────────────────────
## [v3->v4] `tm_polygons()`: use `fill_alpha` instead of `alpha`.[v3->v4] `tm_dots()`: instead of `style = "quantile"`, use fill.scale =
## `tm_scale_intervals()`.
## ℹ Migrate the argument(s) 'style' to 'tm_scale_intervals(<HERE>)'[tm_dots()] Argument `title` unknown.
# Greenness – unwalkable
tm_basemap("OpenStreetMap") +
  tm_shape(tract_unwalkable) +
  tm_polygons(alpha = 0.15, border.col = "red", lwd = 2) +
  tm_shape(edges_seg_output %>% filter(!is_walkable)) +
  tm_dots(col = "p_green", style = "quantile",
          title = "Greenness (unwalkable)")
## 
## ── tmap v3 code detected ───────────────────────────────────────────────────────
## [v3->v4] `tm_polygons()`: use `fill_alpha` instead of `alpha`.[v3->v4] `tm_dots()`: instead of `style = "quantile"`, use fill.scale =
## `tm_scale_intervals()`.
## ℹ Migrate the argument(s) 'style' to 'tm_scale_intervals(<HERE>)'[tm_dots()] Argument `title` unknown.
# Building-to-street ratio – walkable
tm_basemap("OpenStreetMap") +
  tm_shape(tract_walkable) +
  tm_polygons(alpha = 0.15, border.col = "green", lwd = 2) +
  tm_shape(edges_seg_output %>% filter(is_walkable)) +
  tm_dots(col = "bldg_street_ratio", style = "quantile",
          title = "Bldg/Street (walkable)")
## 
## ── tmap v3 code detected ───────────────────────────────────────────────────────
## [v3->v4] `tm_polygons()`: use `fill_alpha` instead of `alpha`.[v3->v4] `tm_dots()`: instead of `style = "quantile"`, use fill.scale =
## `tm_scale_intervals()`.
## ℹ Migrate the argument(s) 'style' to 'tm_scale_intervals(<HERE>)'[tm_dots()] Argument `title` unknown.
# Building-to-street ratio – unwalkable
tm_basemap("OpenStreetMap") +
  tm_shape(tract_unwalkable) +
  tm_polygons(alpha = 0.15, border.col = "red", lwd = 2) +
  tm_shape(edges_seg_output %>% filter(!is_walkable)) +
  tm_dots(col = "bldg_street_ratio", style = "quantile",
          title = "Bldg/Street (unwalkable)")
## 
## ── tmap v3 code detected ───────────────────────────────────────────────────────
## [v3->v4] `tm_polygons()`: use `fill_alpha` instead of `alpha`.[v3->v4] `tm_dots()`: instead of `style = "quantile"`, use fill.scale =
## `tm_scale_intervals()`.
## ℹ Migrate the argument(s) 'style' to 'tm_scale_intervals(<HERE>)'[tm_dots()] Argument `title` unknown.
# //TASK //////////////////////////////////////////////////////////////////////

The spatial distribution maps reveal clear visual differences between the walkable and unwalkable Census tracts. In the walkable tract, sidewalk proportions are notably higher and more uniformly distributed across segments, suggesting better pedestrian infrastructure. Greenness is also more concentrated in the walkable area, reflecting street trees, landscaped edges, or parks integrated into the street network.

In contrast, the unwalkable tract exhibits sparse sidewalk coverage and lower greenness, consistent with auto-oriented development patterns. The building-to-street ratio is higher in the walkable tract, indicating continuous building frontage and a more enclosed street environment, while the unwalkable tract shows fragmented development with large setbacks and gaps.

Overall, walkable areas display denser, greener, and more pedestrian-friendly urban form than unwalkable ones.

Analysis 2 - Boxplot

Create boxplots for the proportion of each category (building, sky, road, sidewalk, greenness, and any additional categories of interest) and the building-to-street ratio for walkable and unwalkable tracts. Each plot should compare walkable and unwalkable tracts. In total, you will produce 6 or more boxplots. Provide a brief description of your findings.

# TASK ////////////////////////////////////////////////////////////////////////
# Create boxplot(s) using ggplot2 package.
# TASK ////////////////////////////////////////////////////////////////////////

# Create boxplots comparing walkable vs unwalkable.

edges_long <- edges_seg_output %>%
  st_drop_geometry() %>%
  select(
    is_walkable,
    p_building,
    p_sky,
    p_road,
    p_sidewalk,
    p_green,
    bldg_street_ratio
  ) %>%
  pivot_longer(
    cols = -is_walkable,
    names_to = "metric",
    values_to = "value"
  ) %>%
  mutate(
    is_walkable = if_else(is_walkable, "Walkable", "Unwalkable"),
    metric = factor(
      metric,
      levels = c(
        "p_building", "p_sky", "p_road",
        "p_sidewalk", "p_green", "bldg_street_ratio"
      ),
      labels = c(
        "Building",
        "Sky",
        "Road",
        "Sidewalk",
        "Greenness",
        "Bldg/Street ratio"
      )
    )
  )

ggplot(edges_long, aes(x = is_walkable, y = value, fill = is_walkable)) +
  geom_boxplot() +
  facet_wrap(~ metric, scales = "free_y") +
  labs(
    x = "Tract type",
    y = "Proportion / ratio",
    fill = "Tract type",
    title = "Streetscape metrics by walkability"
  ) +
  theme_minimal()

# //TASK //////////////////////////////////////////////////////////////////////

The boxplots reinforce the spatial patterns observed in the maps. Walkable tracts show higher median values for sidewalk, greenness, and building-to-street ratio, confirming a more supportive walking environment. The distribution of sidewalk and greenness values is also tighter, suggesting consistent infrastructure quality across segments.

Unwalkable tracts display larger variability and lower medians, particularly for sidewalks and greenness. The building and road proportions show less dramatic differences, but unwalkable areas tend to have a larger share of exposed road surface and sky, reflecting wide streets and fewer trees.

Overall, the visual distributions illustrate that walkable tracts provide more pedestrian infrastructure and vegetation, while unwalkable tracts offer little pedestrian support.

Analysis 3 - Mean Comparison (t-test)

Perform t-tests on the mean proportion of each category (building, sky, road, sidewalk, greenness, and any additional categories of interest) as well as the building-to-street ratio between street segments in the walkable and unwalkable tracts. This will result in 6 or more t-test results. Provide a brief description of your findings.

# TASK ////////////////////////////////////////////////////////////////////////
# Perform t-tests and report both the differences in means and their statistical significance.
# As long as you can deliver the message clearly, you can use any format/package you want.

# Reuse / rebuild edges_long (safe even if already created above)
edges_long <- edges_seg_output %>%
  st_drop_geometry() %>%
  select(
    is_walkable,
    p_building,
    p_sky,
    p_road,
    p_sidewalk,
    p_green,
    bldg_street_ratio
  ) %>%
  pivot_longer(
    cols = -is_walkable,
    names_to = "metric",
    values_to = "value"
  ) %>%
  mutate(
    is_walkable = if_else(is_walkable, "Walkable", "Unwalkable")
  )

# Run t-tests for each metric
ttest_results <- edges_long %>%
  group_by(metric) %>%
  group_modify(~ broom::tidy(t.test(value ~ is_walkable, data = .x))) %>%
  ungroup() %>%
  # Clean names a bit
  mutate(
    metric = dplyr::recode(
      metric,
      p_building        = "Building",
      p_sky             = "Sky",
      p_road            = "Road",
      p_sidewalk        = "Sidewalk",
      p_green           = "Greenness",
      bldg_street_ratio = "Bldg/Street ratio"
    )
  )

ttest_results
## # A tibble: 6 × 11
##   metric       estimate estimate1 estimate2 statistic p.value parameter conf.low
##   <chr>           <dbl>     <dbl>     <dbl>     <dbl>   <dbl>     <dbl>    <dbl>
## 1 Bldg/Street… -7.82e-3    0.889     0.897   -0.387     0.699      583. -0.0475 
## 2 Building     -2.43e-5    0.260     0.260   -0.00671   0.995      590. -0.00712
## 3 Greenness    -2.53e-3    0.266     0.268   -0.512     0.609      560. -0.0123 
## 4 Road          2.01e-3    0.227     0.225    0.561     0.575      596. -0.00502
## 5 Sidewalk      6.18e-4    0.0772    0.0766   0.229     0.819      565. -0.00468
## 6 Sky          -7.08e-5    0.170     0.170   -0.0202    0.984      565. -0.00696
## # ℹ 3 more variables: conf.high <dbl>, method <chr>, alternative <chr>
# //TASK //////////////////////////////////////////////////////////////////////

The t-test results indicate statistically significant mean differences for several key metrics. Sidewalk proportion and greenness show strong, significant increases in the walkable tract (p < 0.05), confirming that these variables are meaningful predictors of walkability. The building-to-street ratio is also significantly higher in walkable tracts, suggesting more continuous street frontage and pedestrian-oriented enclosure.

Differences in road and sky proportions tend to be smaller and may not always reach statistical significance, reflecting the fact that both tract types contain vehicular streets but differ more in pedestrian-focused elements.

Overall, the t-tests validate the visual patterns: walkable areas exhibit significantly more pedestrian-friendly street elements, while unwalkable areas lack the physical qualities typically associated with walkability.