# Pull stream network associated with a waterbody catchment

#### Jemma Stachelek

#### 2023-08-11

The goal of this vignette is to demonstrate how to pull the stream network associated with a waterbody catchment. We will use the `extract_network` function to accomplish this task using the built-in `mendota` dataset.

    library(nhdR)
    library(dplyr)
    library(ggplot2)
    library(sf)

Let’s start by pulling the coordinates associated with Lake Mendota, which will be the largest object (by area) in the waterbody object.

    data(mendota)

    largest_waterbody <- which.max(st_area(mendota$sp$NHDWaterbody))
    #> old-style crs object detected; please recreate object with a recent sf::st_crs()
    #> old-style crs object detected; please recreate object with a recent sf::st_crs()
    #> old-style crs object detected; please recreate object with a recent sf::st_crs()
    mendota_lake      <- mendota$sp$NHDWaterbody[largest_waterbody, ]
    #> old-style crs object detected; please recreate object with a recent sf::st_crs()
    #> old-style crs object detected; please recreate object with a recent sf::st_crs()
    mendota_lake      <- st_transform(mendota_lake, crs = 4326)
    mendota_centroid  <- st_coordinates(st_centroid(mendota_lake))

Next, we can use the `extract_network` function to pull the stream network associated with Lake Mendota. Notice that we have set the `maxsteps` parameter to Inf. If the network is anticipated to be very large it can be a good idea to set this to a discrete (lower) number to avoid returning very large lines objects.

    mendota_network <- extract_network(lon = mendota_centroid[1],
      lat = mendota_centroid[2],
      maxsteps = Inf)

Finally, we compare the stream network from a geometric buffer around Lake Mendota against the output of `extract_network` to make sure everything is working properly.

    ggplot() +
      geom_sf(data = mendota$sp$NHDFlowLine) +
      geom_sf(data = mendota_lake, fill = "cyan") +
      geom_sf(data = mendota_network, color = "blue")
    #> old-style crs object detected; please recreate object with a recent sf::st_crs()
    #> old-style crs object detected; please recreate object with a recent sf::st_crs()
    #> old-style crs object detected; please recreate object with a recent sf::st_crs()