Major Assignment 2: Comparing Streetscapes and Walkability

Thomas Otoo

2026-11-21

knitr::opts_chunk$set(message = FALSE, warning = FALSE)

# Load the packages used in your analysis.
library(tidyverse)
library(magrittr)
library(sf)
library(tidycensus)
library(osmdata)
library(sfnetworks)
library(tidygraph)
library(leaflet)
library(leafsync)
library(glue)
library(knitr)

How to Use This Starter File

Complete the blank code chunks, provide explanations where requested, and add code comments where necessary. Keep the existing code chunks and section headings. Use methods from class and the course labs; code needed to preserve your inputs is supplied.

Work through the file in order:

  1. Fill in the data-preparation chunks marked eval=FALSE and run them manually in RStudio.
  2. Run save-inputs to save your sample, then complete image collection and Colab processing in Section 4.
  3. Complete the analysis and knit. Leave eval=FALSE in place: the report loads your saved inputs instead of resampling roads or downloading images again.

Save this Rmd, major2_inputs.rds, and the downloaded seg_output.csv in the same project folder. Use a downloaded_image subfolder for the JPG files. Open an RStudio project in that folder so relative paths work both interactively and when knitting. Do not include private credentials in the document.

Assignment Overview

Select two Census tracts that you expect to differ in walkability. Compare their streetscapes using images randomly sampled from each road network. Then compare the tracts within road classes represented in both samples. Does your interpretation change when you compare similar kinds of roads?

The labels “More walkable” and “Less walkable” describe your initial expectations, not a conclusion established by the model. Image composition captures only some aspects of walkability.

Analysis Settings and Sampling Rules

  • Choose exactly two different Census tracts within Fulton or DeKalb County, Georgia: one you expect to be more walkable and one you expect to be less walkable. Use 2024 tract geometry; the 2024 ACS 5-year methods from the labs can provide it. Demographic estimates are not required.
  • Include primary, secondary, tertiary, and residential roads. Exclude other OSM classes, including connector roads.
  • Clean undirected networks using the OSM lab methods. When smoothing, preserve road-class changes with require_equal = "highway" and retain attributes with summarise_attributes = "first".
  • An eligible segment must be at least 300 feet (91.44 meters) long. Keep eligible segments whole; do not clip them at the tract boundary.
  • Randomly sample up to 100 eligible segments per tract. Use all eligible segments if fewer than 100 are available. Use the fixed seed below and a consistent ordering before sampling.
  • Sample across all eligible roads in each tract, not separately within road classes. Differences in road composition are part of the comparison.
  • Collect two images per segment at its midpoint, looking toward each end of the segment. Use the lab’s settings: 640 by 640 pixels, fov=90, and pitch=0.
  • Use complete image pairs for segment-level comparisons. Do not replace missing images or measurements with zeros or draw replacement segments after seeing the results.
local_crs <- 32616 # PCS / WGS84 / UTM 16N
sampling_seed <- 2026

1. Select Two Tracts

Download tract geometry and choose one tract you expect to be more walkable and another you expect to be less walkable. Your choices can reflect personal experience, a preliminary map review, or another stated reason.

Create tracts, an sf object with two polygon features and columns GEOID and tract_label. GEOID identifies the tract; tract_label records your initial walkability expectation – use the labels "More walkable" and "Less walkable" throughout the analysis.

# Download the tract geometry and select the two tracts.
# 2024 ACS 5-year tract geometry, as in the labs (total population is only
# requested because get_acs() needs a variable; it is not used).
fd_tracts <- get_acs(geography = "tract",
                     state = "GA",
                     county = c("Fulton", "DeKalb"),
                     variables = c(pop = "B01001_001"),
                     year = 2024,
                     survey = "acs5",
                     geometry = TRUE,
                     output = "wide")

# Pick each tract by a known location inside it (lon, lat):
# - Fox Theatre on Peachtree Street, Midtown Atlanta (Fulton)
# - The Mall at Stonecrest off I-20, Stonecrest (DeKalb)
tract_points <- tibble(
  tract_label = c("More walkable", "Less walkable"),
  lon = c(-84.3857, -84.0948),
  lat = c( 33.7725,  33.7036)
) %>%
  st_as_sf(coords = c("lon", "lat"), crs = 4326) %>%
  st_transform(st_crs(fd_tracts))

# Spatial join attaches the GEOID of the tract that contains each point.
picked <- st_join(tract_points, fd_tracts %>% select(GEOID))

# Assign tract labels and transform to local_crs for spatial calculations.
tracts <- fd_tracts %>%
  select(GEOID) %>%
  inner_join(picked %>% st_drop_geometry(), by = "GEOID") %>%
  mutate(tract_label = factor(tract_label,
                              levels = c("More walkable", "Less walkable"))) %>%
  arrange(tract_label) %>%
  mutate(tract_label = as.character(tract_label)) %>%
  st_transform(local_crs)

tracts %>% st_drop_geometry()

Briefly explain your choices and what streetscape differences you expect to find (no more than 100 words).

Your explanation: For the more walkable tract I chose the one containing the Fox Theatre in Midtown Atlanta. It has a tight street grid, mid- and high-rise buildings along Peachtree Street, continuous sidewalks and MARTA rail nearby. For the less walkable tract I chose the one containing The Mall at Stonecrest in DeKalb County, an area built around wide arterials next to I-20, large parking lots and cul-de-sac subdivisions. I expect the Midtown images to show more building and sidewalk pixels and a higher building-to-street ratio, and the Stonecrest images to show more sky, road and greenness.

2. Prepare and Sample the Road Networks

For each tract:

  1. Download the selected road classes using the tract’s bounding box and clean the network using the lab methods.
  2. Calculate segment lengths. Keep whole segments at least 91.44 meters long whose midpoints fall inside the tract.
  3. Inspect the number of eligible segments by road class.
  4. Use sampling_seed and a consistent row order to sample up to 100 segments across all eligible road classes. Use all segments if fewer than 100 are eligible.

Combine the two samples into edges, an sf object of LINESTRING features in local_crs. Keep tract_label, GEOID, highway, and length (meters). Assign a unique edge_id to each segment across the combined sample.

# Download and clean the road networks for the two tracts.
road_classes <- c("primary", "secondary", "tertiary", "residential")

# Download OSM roads for one bounding box (lat/lon). If the main Overpass
# server is busy (e.g. HTTP 502), try the backup server used in the OSM lab.
get_osm_roads <- function(bb) {
  servers <- c("https://overpass-api.de/api/interpreter",
               "https://overpass.private.coffee/api/interpreter")
  for (s in servers) {
    set_overpass_url(s)
    out <- tryCatch(
      opq(bbox = bb, timeout = 180) %>%
        add_osm_feature(key = "highway", value = road_classes) %>%
        osmdata_sf() %>%
        osm_poly2line(),
      error = function(e) { message("Overpass failed at ", s, ": ", conditionMessage(e)); NULL })
    if (!is.null(out)) return(out)
    Sys.sleep(5)
  }
  stop("All Overpass servers failed. Try again in a few minutes.")
}

# Build a clean, undirected network for one tract and return its eligible edges.
prepare_tract_roads <- function(tract) {
  bb <- tract %>% st_transform(4326) %>% st_bbox()

  net <- get_osm_roads(bb)$osm_lines %>%
    filter(highway %in% road_classes) %>%   # drop any other classes returned
    select(osm_id, highway) %>%
    st_transform(local_crs) %>%
    as_sfnetwork(directed = FALSE) %>%
    activate("edges") %>%
    filter(!edge_is_multiple()) %>%          # remove duplicated edges
    filter(!edge_is_loop()) %>%              # remove loops
    convert(to_spatial_subdivision) %>%      # split edges at shared vertices
    convert(to_spatial_smooth,               # remove pseudo nodes
            require_equal = "highway",
            summarise_attributes = "first")

  # Calculate lengths and retain segments with eligible midpoints and lengths.
  edges_all <- net %>%
    st_as_sf("edges") %>%
    select(osm_id, highway) %>%
    mutate(length = as.numeric(st_length(.))) %>%
    filter(length >= 91.44)                  # at least 300 feet; kept whole

  # The midpoint (50% along the line) decides whether a segment belongs to the tract.
  midpoints <- edges_all %>%
    st_line_sample(sample = 0.5) %>%
    st_cast("POINT")
  in_tract <- lengths(st_intersects(midpoints, tract)) > 0

  edges_all[in_tract, ] %>%
    mutate(GEOID = tract$GEOID,
           tract_label = tract$tract_label)
}

eligible <- map(seq_len(nrow(tracts)), ~ prepare_tract_roads(tracts[.x, ]))

# Inspect eligible counts before sampling.
eligible %>%
  bind_rows() %>%
  st_drop_geometry() %>%
  count(tract_label, highway) %>%
  pivot_wider(names_from = tract_label, values_from = n, values_fill = 0)

# Use sampling_seed to randomly sample up to 100 segments per tract.
# Rows are sorted the same way every time so the seed gives the same sample.
sample_tract <- function(eligible_edges) {
  set.seed(sampling_seed)
  eligible_edges %>%
    arrange(highway, osm_id, length) %>%
    slice_sample(n = min(100, nrow(eligible_edges)))
}

# Combine the samples and assign unique edge IDs.
edges <- eligible %>%
  map(sample_tract) %>%
  bind_rows() %>%
  st_cast("LINESTRING") %>%
  mutate(edge_id = seq_len(nrow(.))) %>%
  select(edge_id, tract_label, GEOID, highway, length, osm_id)

table(edges$tract_label, edges$highway)

3. Prepare the Image Locations and Headings

Adapt getHeading() from the GSV lab to take one projected LINESTRING and return two midpoint views. Sample points at 0.48, 0.50, and 0.52 along the segment. From the midpoint (0.50), calculate headings toward the other two points, looking toward each end of the segment.

Return two rows with type ("mid1" and "mid2"), X, Y, and heading. Use the midpoint coordinates for both rows and express headings from 0 to less than 360 degrees.

getHeading <- function(line) {
  # Locate the midpoint and the nearby points used for heading calculations.
  mid_p3 <- line %>%
    st_sfc() %>%  # one LINESTRING in local_crs coordinates
    st_line_sample(sample = c(0.48, 0.5, 0.52)) %>%
    st_cast("POINT") %>%
    st_coordinates()

  mid_p <- mid_p3[2, ]

  # Calculate both viewing directions and return their locations and headings.
  # atan2(dx, dy) gives the compass bearing (0 = north, clockwise) in radians.
  mid_heading_1 <- atan2(mid_p3[1, "X"] - mid_p3[2, "X"],
                         mid_p3[1, "Y"] - mid_p3[2, "Y"]) * 180 / pi  # toward the 0.48 end
  mid_heading_2 <- atan2(mid_p3[3, "X"] - mid_p3[2, "X"],
                         mid_p3[3, "Y"] - mid_p3[2, "Y"]) * 180 / pi  # toward the 0.52 end

  tribble(
    ~type,  ~X,          ~Y,          ~heading,
    "mid1", mid_p["X"],  mid_p["Y"],  mid_heading_1 %% 360,
    "mid2", mid_p["X"],  mid_p["Y"],  mid_heading_2 %% 360
  )
}

Apply the function to edges and create edges_heading. Create points using local_crs, and transform them to EPSG:4326. Update X and Y to longitude and latitude after transforming. Assign unique img_id values across both tracts. Colab extracts the image ID from the filename and preserves it in the CSV.

edges_heading must have two POINT rows per sampled segment and contain edge_id, img_id, tract_label, GEOID, highway, type, X, Y, and heading.

# Apply getHeading() and attach the segment attributes.
edges_heading <- edges %>%
  st_geometry() %>%
  map_df(getHeading, .progress = TRUE) %>%
  bind_cols(edges %>%
              st_drop_geometry() %>%
              select(edge_id, tract_label, GEOID, highway) %>%
              slice(rep(seq_len(nrow(edges)), each = 2)))  # two views per segment

# Transform the points, update longitude/latitude, and assign image IDs.
edges_heading <- edges_heading %>%
  st_as_sf(coords = c("X", "Y"), crs = local_crs, remove = FALSE) %>%
  st_transform(4326) %>%
  mutate(X = st_coordinates(.)[, "X"],   # longitude
         Y = st_coordinates(.)[, "Y"],   # latitude
         img_id = seq_len(nrow(.))) %>%
  select(edge_id, img_id, tract_label, GEOID, highway, type, X, Y, heading)

nrow(edges_heading) == 2 * nrow(edges)

Run the supplied save chunk manually after preparing your sample. If you change the tracts or sampling before collecting images, regenerate and save the inputs together. Once image collection starts, keep the IDs fixed.

# Provided: run once after preparing your inputs.
saveRDS(
  list(tracts = tracts, edges = edges, edges_heading = edges_heading),
  "major2_inputs.rds"
)
# Provided: restore the same inputs when knitting.
saved_inputs <- readRDS("major2_inputs.rds")
tracts <- saved_inputs$tracts
edges <- saved_inputs$edges
edges_heading <- saved_inputs$edges_heading

stopifnot(nrow(tracts) == 2, !anyDuplicated(tracts$GEOID))
stopifnot(setequal(tracts$tract_label, c("More walkable", "Less walkable")))
stopifnot(!anyNA(edges$edge_id), !anyDuplicated(edges$edge_id))
stopifnot(nrow(edges_heading) == 2 * nrow(edges))
stopifnot(!anyNA(edges_heading$img_id), !anyDuplicated(edges_heading$img_id))
stopifnot(!anyNA(edges_heading$edge_id), !anyNA(edges_heading$type))
stopifnot(setequal(edges_heading$edge_id, edges$edge_id))

# Each sampled segment must have exactly one view of each type.
view_counts <- edges_heading %>%
  sf::st_drop_geometry() %>%
  dplyr::group_by(edge_id) %>%
  dplyr::summarise(
    n_views = dplyr::n(),
    n_mid1 = sum(type == "mid1"),
    n_mid2 = sum(type == "mid2"),
    .groups = "drop"
  )
stopifnot(all(view_counts$n_views == 2L),
          all(view_counts$n_mid1 == 1L),
          all(view_counts$n_mid2 == 1L))

Create an interactive map showing both selected tracts with clearly identified tract labels. Include this map in the knitted report.

# Map the selected tract polygons and identify the two tracts.
tracts_4326 <- tracts %>%
  st_transform(4326) %>%
  mutate(tract_label = factor(tract_label, levels = c("More walkable", "Less walkable")))

tract_pal <- colorFactor(c("#1764AB", "#C43C39"),
                         levels = c("More walkable", "Less walkable"))

leaflet(tracts_4326) %>%
  addProviderTiles(providers$CartoDB.Positron) %>%
  addPolygons(fillColor = ~tract_pal(tract_label), fillOpacity = 0.45,
              color = "black", weight = 2,
              label = ~paste0(tract_label, " (GEOID ", GEOID, ")"),
              labelOptions = labelOptions(noHide = TRUE, direction = "top",
                                          textsize = "13px")) %>%
  addLegend(position = "bottomright", pal = tract_pal,
            values = ~tract_label, title = "Initial expectation")

4. Download Images and Run Colab

Adapt getImage() from the GSV lab to download one image from one row of edges_heading:

  1. Extract type, img_id, edge_id, and heading. Format location as latitude,longitude (Y,X).
  2. Read your Google API key from its environment variable and construct request using the lab’s Street View Static API endpoint and image settings.
  3. Set fpath to the supplied filename inside downloaded_image.

The filename and download commands are provided below.

getImage <- function(iterrow) {
  # Extract row values, format location and heading, and construct the request URL.
  type <- iterrow$type
  img_id <- iterrow$img_id
  edge_id <- iterrow$edge_id
  location <- paste0(iterrow$Y %>% round(5), ",", iterrow$X %>% round(5))  # lat,lon
  heading <- iterrow$heading %>% round(1)
  key <- Sys.getenv("google_api")  # key stored in .Renviron, never typed here

  endpoint <- "https://maps.googleapis.com/maps/api/streetview"
  request <- glue::glue("{endpoint}?size=640x640&location={location}&heading={heading}&fov=90&pitch=0&key={key}")

  # Provided filename: keep img_id as the first number in the filename.
  fname <- glue::glue("GSV-img_{img_id}-eid_{edge_id}-type_{type}.jpg")

  # Create fpath by combining the output folder with fname.
  fpath <- file.path("downloaded_image", fname)

  # Provided: skip an existing file rather than request it again.
  if (!file.exists(fpath)) {
    download.file(request, fpath, mode = "wb", quiet = TRUE)
    Sys.sleep(1)
  }
}

Run the supplied download chunk manually, keeping eval=FALSE. Inspect the images and remove gray “no imagery” placeholders or invalid files before running Colab. Do not change or reuse image IDs to fill gaps. Contact me if technical problems prevent you from completing collection or processing.

# Provided: run manually, not when knitting.
dir.create("downloaded_image", showWarnings = FALSE)
for (i in seq_len(nrow(edges_heading))) {
  getImage(edges_heading[i, ])
}

Zip the image folder as gsv_images.zip. Use the Colab notebook shared for the computer-vision lab (https://colab.research.google.com/drive/1s0HiZIwjke-xtmHwzFmFp6PJrNkysoy9), set the extracted image-folder path, run segmentation on all images, and download seg_output.csv to your project folder. Running the supplied Python is required; writing Python or changing the model is not assessed. Do not include the notebook’s demonstration outputs or individual image predictions in this report.

5. Join Results and Create Segment-Level Measures

Read seg_output.csv and join it to edges_heading using the shared img_id column. Create image_results, with one row per matching image and the original segment and tract attributes.

Determine the total number of pixels in the output mask from Colab or by summing all category counts for one image, as in the lab. Use that total to calculate these six image-level measures. As in the lab, the five pct_* measures are percentages from 0 to 100; multiply the pixel fractions by 100 and label their plots and tables accordingly. The building-to-street ratio is not a percentage:

  • pct_building: (building pixels / total pixels) * 100.
  • pct_sky: (sky pixels / total pixels) * 100.
  • pct_road: (road pixels / total pixels) * 100.
  • pct_sidewalk: (sidewalk pixels / total pixels) * 100.
  • pct_greenness: ((vegetation pixels + terrain pixels) / total pixels) * 100.
  • b2s_ratio: building pixels divided by road + sidewalk + car pixels. Apply the lab’s rule: set the ratio to NA_real_ when the street-pixel total is zero, or the ratio exceeds 4. Apply this rule to each image before averaging the views.
# Read the CSV, join image IDs to locations, and calculate image-level measures.
seg_output <- read.csv("seg_output.csv")

# The 19 Cityscapes categories returned by the Colab model.
seg_classes <- c("road", "sidewalk", "building", "wall", "fence", "pole",
                 "traffic.light", "traffic.sign", "vegetation", "terrain",
                 "sky", "person", "rider", "car", "truck", "bus", "train",
                 "motorcycle", "bicycle")

# Total pixels in the output mask = sum of all category counts for one image.
total_pixels <- seg_output %>%
  slice(1) %>%
  select(all_of(seg_classes)) %>%
  sum()
total_pixels
## [1] 589824
measures <- c("pct_building", "pct_sky", "pct_road",
              "pct_sidewalk", "pct_greenness", "b2s_ratio")

image_results <- edges_heading %>%
  inner_join(seg_output %>% select(img_id, all_of(seg_classes)), by = "img_id") %>%
  mutate(pct_building = building / total_pixels * 100,
         pct_sky = sky / total_pixels * 100,
         pct_road = road / total_pixels * 100,
         pct_sidewalk = sidewalk / total_pixels * 100,
         pct_greenness = (vegetation + terrain) / total_pixels * 100,
         street_pixels = road + sidewalk + car,
         b2s_ratio = building / street_pixels,
         # Lab rule, applied per image: no street pixels or ratio above 4 -> NA
         b2s_ratio = if_else(street_pixels == 0 | b2s_ratio > 4, NA_real_, b2s_ratio))

# How many planned images have a segmentation result, by tract
image_results %>%
  st_drop_geometry() %>%
  count(tract_label, name = "images_with_results") %>%
  kable()
tract_label images_with_results
Less walkable 182
More walkable 46

Create segment_results, an sf object with one midpoint POINT per segment. Keep only segments with both views (mid1 and mid2) and valid values for all six measures in each view (no missing or infinite values). Keep excluded images in image_results.

Average each image-level measure across the segment’s two views. In particular, average the two image-level building-to-street ratios rather than calculate a new ratio from pooled counts. Keep edge_id, GEOID, tract_label, highway, and the six measure names. Drop geometry before grouping and summarizing measurements, then join the summary back to one midpoint per segment.

# Identify complete pairs with valid measurements.
valid_pairs <- image_results %>%
  st_drop_geometry() %>%
  filter(if_all(all_of(measures), is.finite)) %>%   # drops NA, NaN and Inf
  group_by(edge_id) %>%
  filter(n() == 2, all(c("mid1", "mid2") %in% type)) %>%
  ungroup()

# Average the two views within each segment and restore one midpoint geometry.
segment_summary <- valid_pairs %>%
  group_by(edge_id, GEOID, tract_label, highway) %>%
  summarise(across(all_of(measures), mean), .groups = "drop")

segment_results <- edges_heading %>%
  filter(type == "mid1") %>%          # both views share the midpoint, keep one
  select(edge_id) %>%
  inner_join(segment_summary, by = "edge_id") %>%
  mutate(tract_label = factor(tract_label, levels = c("More walkable", "Less walkable"))) %>%
  select(edge_id, GEOID, tract_label, highway, all_of(measures))

nrow(segment_results)
## [1] 114

6. Compare the Two Tracts Overall

Use segment_results to create:

  1. Interactive maps: Map sidewalk percentage, greenness percentage, and building-to-street ratio. For each measure, show both tracts together or in two separate maps. Use the same color scale for both tracts and include tract boundaries, labels, and legends.
  2. Boxplots: Create one figure with six panels, one per measure. Put tract_label on the x-axis and the measure on the y-axis, giving two boxes per panel. Use readable panel titles. Each panel may have its own y-axis scale, shared by both tracts.
  3. Summary table: Create and display tract_summary with one row per tract. Include the sampled segment count from edges, the included segment count from segment_results, and the mean of each of the six measures for included segments.

If a tract has no valid pairs, report zero included segments and NA means. Show the available results and explain any comparisons you cannot make. If neither tract has valid pairs, skip the measure maps and boxplots. Keep the code chunks and required columns in empty result objects.

# Map the three measures and make the two tracts easy to compare.
measure_labels <- c(pct_building = "Building (%)",
                    pct_sky = "Sky (%)",
                    pct_road = "Road (%)",
                    pct_sidewalk = "Sidewalk (%)",
                    pct_greenness = "Greenness (%)",
                    b2s_ratio = "Building-to-street ratio")

# One map per tract; both maps for a measure use the same palette and domain.
map_one_tract <- function(var, label, pal) {
  tract_poly <- tracts_4326 %>% filter(tract_label == label)
  pts <- segment_results %>% filter(tract_label == label)

  m <- leaflet() %>%
    addProviderTiles(providers$CartoDB.Positron) %>%
    addPolygons(data = tract_poly, fill = FALSE, color = "black", weight = 2,
                label = ~paste0(tract_label, " (GEOID ", GEOID, ")"),
                labelOptions = labelOptions(noHide = TRUE, direction = "top"))
  if (nrow(pts) > 0) {
    m <- m %>%
      addCircleMarkers(data = pts, radius = 6, stroke = TRUE, color = "#333333",
                       weight = 1, fillOpacity = 0.9,
                       fillColor = pal(pts[[var]]),
                       popup = paste0(pts$highway, ": ", round(pts[[var]], 2)))
  }
  m %>%
    addLegend(position = "bottomright", pal = pal,
              values = segment_results[[var]],
              title = paste0(label, "<br>", measure_labels[[var]]))
}

map_measure <- function(var, colors) {
  # Shared color scale: domain from both tracts together
  pal <- colorNumeric(colors, domain = segment_results[[var]])
  latticeview(map_one_tract(var, "More walkable", pal),
              map_one_tract(var, "Less walkable", pal),
              ncol = 2, sync = "none")
}

if (nrow(segment_results) > 0) {
  htmltools::tagList(
    htmltools::h4("Sidewalk (%)"),
    map_measure("pct_sidewalk", c("#f7f4f9", "#c994c7", "#ce1256", "#67001f")),
    htmltools::h4("Greenness (%)"),
    map_measure("pct_greenness", c("darkgray", "yellow", "green", "darkgreen")),
    htmltools::h4("Building-to-street ratio"),
    map_measure("b2s_ratio", c("#EED8AE", "#C4A484", "#8B5A2B", "brown"))
  )
}

Sidewalk (%)

Greenness (%)

Building-to-street ratio

# Compare all six segment-level measures between tracts.
if (nrow(segment_results) > 0) {
  segment_results %>%
    st_drop_geometry() %>%
    pivot_longer(cols = all_of(measures), names_to = "variable", values_to = "value") %>%
    mutate(variable = factor(variable, levels = measures)) %>%
    ggplot(aes(x = tract_label, y = value, fill = tract_label)) +
    geom_boxplot(na.rm = TRUE, show.legend = FALSE) +
    stat_summary(fun = mean, geom = "point", size = 1.5, color = "black", na.rm = TRUE) +
    scale_x_discrete(drop = FALSE) +
    scale_fill_manual(values = c("More walkable" = "#1764AB", "Less walkable" = "#C43C39")) +
    facet_wrap(~variable, scales = "free_y", nrow = 2,
               labeller = as_labeller(measure_labels)) +
    theme_bw() +
    labs(x = NULL, y = "Image percentage (0-100) / building-to-street ratio",
         title = "Segment-level streetscape measures by tract",
         subtitle = "Black dots show means")
}

# Display sampled and included segment counts and mean measures by tract.
sampled_counts <- edges %>%
  st_drop_geometry() %>%
  count(GEOID, tract_label, name = "sampled_segments")

included_means <- segment_results %>%
  st_drop_geometry() %>%
  group_by(GEOID) %>%
  summarise(included_segments = n(),
            across(all_of(measures), mean),
            .groups = "drop")

# Start from the two tracts so a tract with no valid pairs still gets a row.
tract_summary <- tracts %>%
  st_drop_geometry() %>%
  select(GEOID, tract_label) %>%
  left_join(sampled_counts %>% select(-tract_label), by = "GEOID") %>%
  left_join(included_means, by = "GEOID") %>%
  mutate(sampled_segments = replace_na(sampled_segments, 0L),
         included_segments = replace_na(included_segments, 0L)) %>%
  arrange(factor(tract_label, levels = c("More walkable", "Less walkable")))

tract_summary %>%
  kable(digits = 2,
        col.names = c("GEOID", "Tract", "Sampled segments", "Included segments",
                      "Building (%)", "Sky (%)", "Road (%)", "Sidewalk (%)",
                      "Greenness (%)", "Building-to-street ratio"))
GEOID Tract Sampled segments Included segments Building (%) Sky (%) Road (%) Sidewalk (%) Greenness (%) Building-to-street ratio
13121001205 More walkable 23 23 20.54 10.68 35.37 5.06 24.13 0.50
13089023317 Less walkable 100 91 3.37 23.39 32.70 2.08 36.76 0.09

7. Examine Road Composition and Compare Shared Classes

Create and display road_composition from edges, using the original sample before exclusions. For each tract and road class, report the segment count and its proportion of that tract’s sampled segments. Note any of the four selected road classes missing from a tract’s sample; rows for absent classes are optional.

Using segment_results, keep road classes represented in both tracts. Create one figure with six panels, one for each measure. In each panel, put road class on the x-axis and the measure on the y-axis. For each road class, show side-by-side boxplots for “More walkable” and “Less walkable,” using different colors for tract_label. Each panel may use its own y-axis scale, but both tracts must share the same scale within that panel.

Also report the number of included segments by tract and road class in a table. Note any comparisons based on very few segments. If no road classes are shared, explain this and skip the figure.

road_levels <- c("residential", "tertiary", "secondary", "primary")

# Summarize sampled road-class counts and proportions within each tract.
# complete() adds zero rows so a class missing from a tract's sample is visible.
road_composition <- edges %>%
  st_drop_geometry() %>%
  mutate(tract_label = factor(tract_label, levels = c("More walkable", "Less walkable")),
         highway = factor(highway, levels = road_levels)) %>%
  count(tract_label, highway, name = "segments", .drop = FALSE) %>%
  group_by(tract_label) %>%
  mutate(proportion = segments / sum(segments)) %>%
  ungroup()

road_composition %>%
  kable(digits = 3, col.names = c("Tract", "Road class", "Sampled segments", "Proportion of tract sample"))
Tract Road class Sampled segments Proportion of tract sample
More walkable residential 12 0.522
More walkable tertiary 0 0.000
More walkable secondary 11 0.478
More walkable primary 0 0.000
Less walkable residential 76 0.760
Less walkable tertiary 12 0.120
Less walkable secondary 10 0.100
Less walkable primary 2 0.020
# Identify shared classes in segment_results and report their included counts.
included_by_class <- segment_results %>%
  st_drop_geometry() %>%
  mutate(highway = factor(highway, levels = road_levels)) %>%
  count(highway, tract_label, name = "included", .drop = FALSE) %>%
  pivot_wider(names_from = tract_label, values_from = included, values_fill = 0)

included_by_class %>% kable(caption = "Included segments by road class and tract")
Included segments by road class and tract
highway More walkable Less walkable
residential 12 67
tertiary 0 12
secondary 11 10
primary 0 2
shared_classes <- segment_results %>%
  st_drop_geometry() %>%
  group_by(highway) %>%
  filter(n_distinct(tract_label) == 2) %>%
  pull(highway) %>%
  unique()
shared_classes
## [1] "residential" "secondary"
# Compare the tracts within shared road classes for all six measures.
if (length(shared_classes) > 0) {
  segment_results %>%
    st_drop_geometry() %>%
    filter(highway %in% shared_classes) %>%
    mutate(highway = factor(highway, levels = intersect(road_levels, shared_classes))) %>%
    pivot_longer(cols = all_of(measures), names_to = "variable", values_to = "value") %>%
    mutate(variable = factor(variable, levels = measures)) %>%
    ggplot(aes(x = highway, y = value, fill = tract_label)) +
    geom_boxplot(position = position_dodge2(preserve = "single"), na.rm = TRUE) +
    scale_fill_manual(values = c("More walkable" = "#1764AB", "Less walkable" = "#C43C39"),
                      name = "Tract") +
    facet_wrap(~variable, scales = "free_y", nrow = 2,
               labeller = as_labeller(measure_labels)) +
    theme_bw() +
    theme(legend.position = "bottom") +
    labs(x = "Road class", y = "Image percentage (0-100) / building-to-street ratio",
         title = "Streetscape measures within road classes found in both tracts")
} else {
  cat("No road class has included segments in both tracts, so the within-class comparison cannot be made.")
}

Findings

In no more than 200 words, answer:

  • Do the overall results support your initial walkability expectations?
  • How does the mix of sampled road classes differ between the tracts?
  • Does comparing the tracts within the same road classes change your interpretation?

If a comparison is unavailable, explain why and what you can conclude from the available results.

My findings:

The overall results support my expectations. Midtown segments averaged 20.5% building pixels against 3.4% at Stonecrest, 5.1% sidewalk against 2.1%, and a building-to-street ratio of 0.50 against 0.09. Stonecrest images showed more sky (23.4% vs 10.7%) and greenness (36.8% vs 24.1%), which fits its open arterials and wooded subdivisions. Road share was similar (35.4% vs 32.7%), so road pixels did not separate the tracts.

The road mix differs. Midtown had only 23 eligible segments, split between residential (52%) and secondary (48%), with no tertiary or primary roads. Stonecrest’s 100 sampled segments were 76% residential, 12% tertiary, 10% secondary and 2% primary. Nine Stonecrest segments had no Street View imagery and were dropped, leaving 91.

Comparing within residential (12 vs 67 segments) and secondary roads (11 vs 10) does not change the main conclusion. Midtown still has more building, more sidewalk and a higher building-to-street ratio in both classes, and Stonecrest more sky. The greenness gap comes mostly from residential streets; on secondary roads the tracts are close. So part of Stonecrest’s greenness reflects its residential-heavy mix, but the differences in building enclosure and sidewalks do not. The small secondary and Midtown residential groups make those comparisons tentative.