header_tag.html Skip to contents

A new data warehouse contains continuous and daily time series data as cloud-native Parquet files indexed via the USGS Water Data SpatioTemporal Asset Catalog (STAC) API. This new pathway makes it fast and easy to discover and download large amounts of water data. Read the official USGS STAC documentation here.

The most authoritative, up-to-date version of a record can be retrieved from the OGC API services. OGC data are retrieved in the original “read_waterdata” functions. However, if you need lots of data, the new STAC functions are for you!

The files on the STAC system do not necessarily have the latest available data. They get updated frequently, but there’s no promise of when the files get refreshed. If needed, you can fill in more recent data using OGC data.

There are two main pathways to take advantage of this new STAC service:

  1. Classic workflow: functions that return all requested data into your R environment. Because it’s so easy to request a LOT of data, care is needed to prevent running out of memory.

  2. Flexible workflow: functions that give users the ability to search, download, and open STAC data.

Before you start exploring the new functions, we recommend requesting a NEW USGS API token from here: https://api.waterdata.usgs.gov/signup/, and saving it as “STAC_USGS_PAT” in your .Renviron (perhaps using usethis::edit_r_environ()). Don’t remove the “API_USGS_PAT” token though, both will be used. The idea is that the original “API_USGS_PAT” will be used when requesting OGC data, and the “STAC_USGS_PAT” will be used when requesting STAC data. It is perfectly fine to request many different API keys using the same email.

STAC_USGS_PAT = "my_new_token"

The request limits for STAC are much higher than OGC. However, the STAC requests will drain your OGC limits quickly. This is why having separate tokens for each service is recommended.

Classic Workflow

The new functions are read_waterdata_continous_por and read_waterdata_daily_por. The “por” stands for period of record. These functions are especially efficient when you want data spanning the full period of record. These functions are for users who want to pull a “reasonable” amount of data into their R environment. We’ll get into what a “reasonable” amount is below.

read_waterdata_continuous_por

Possibly the best use-case for this new STAC function is for a user who wants the full period of record continuous data for a single site. Using the original OGC functions, this requires looping over many requests because the OGC continuous service limits requests to a 3 year period. In one test, it took 35 minutes to download all the data for a site that had nearly 30 years of continuous sensor data of 8 parameter codes. Using the STAC function, it took ~6 seconds. Here we wrap the call with system.time to show how long it took to retrieve the data:

library(dataRetrieval)

system.time({
  df <- read_waterdata_continuous_por(
    monitoring_location_id = "USGS-0208458892"
)
})
#> user  system elapsed 
#> 4.21    0.69    6.74 

nrow(df)
#> [1] 3104851

Over 3 million rows in seconds - not too bad!

There are more arguments that give you additional flexibility to query your data. Keep in mind that there’s A LOT of continuous data, and it becomes really easy to request more data than R can load into memory.

We built into the function two arguments that will limit your ability to accidentally ask for a ridiculous amount of data. site_limits and memory_MB_limit.

The site_limits argument is set as a default of 100 sites for the continuous data. If the STAC search determines that there will be more than the site_limits, it will not even attempt to request the data.

The memory_MB_limit argument set it as a default as 1000 (so, approximately 1 GB of data returned). If you request more than that, the function will error. You can bump up the memory_MB_limit if you are confident in your computer’s memory.

Here is an example of a request that will fail because the number of sites exceeds the site_limit default:

dane_data <- read_waterdata_continuous_por(
    state_name = "Wisconsin"
)
Error in get_stac_data(args, data_type = data_type, collections = collection,  : 
  Unique monitoring_location_id exceed site_limits

This is fewer sites, but still a LOT of data. This example should fail due to exceeding the memory_MB_limit:

wisconsin_data <- read_waterdata_continuous_por(
    state_name = "Wisconsin",
    county_name = "Dane County",
    parameter_code = "00060",
    site_type = "Stream",
    site_limits = 300
)
Estimated memory size of the dataset:5930.98 MB

Error in check_memory(data_tbl$total_rows, memory_MB_limit, ncol = ncol(df_out)) : 
  Increase the memory_MB_limit parameter to allow this query to be loaded.

read_waterdata_daily_por

Similar to the continuous data, we can now retrieve period of record daily data quicker using the read_waterdata_daily_por function. As an example, we could request all the daily data for a single HUC.

df_huc <- read_waterdata_daily_por(
    hydrologic_unit_code = "07090002",
    parameter_code = "00060"
)
nrow(df_huc)
472886

Further Considerations

Each time you run one of the “por” functions, the code will go to the STAC service, find the files you need, access and load the data into memory. Under the hood, it’s using DuckDB.

If you are asking for large amounts of data, consider using the flexible workflow shown below.

If you need to fill in more recent data, consider querying the OGC data on “last_modified”.

df <- read_waterdata_continuous_por(
  monitoring_location_id = "USGS-01435000",
  parameter_code = "00060")

latest_modified <- max(df$last_modified)
latest_modified
#> [1] "2026-12-01 05:27:17 UTC"

df_new <- read_waterdata_continuous(
  monitoring_location_id = "USGS-01435000",
  parameter_code = "00060",
  # get everything modified after "latest_modified"
  # here we do that by adding a second and
  # leaving the second entry open-ended (NA):
  last_modified = c(latest_modified + 1, NA) 
)

range(df_new$time)
#> [1] "2026-12-01 05:30:00 UTC" "2026-12-01 18:15:00 UTC"

df_all <- df |> 
  dplyr::bind_rows(df_new)

range(df_all$time)
#> [1] "1987-04-01 05:15:00 UTC" "2026-12-01 18:15:00 UTC"

Flexible Workflow

The “por” functions mirror the other read_waterdata functions by loading data directly into your R session. For large requests, you run the risk of maxing out your computer’s internal memory (RAM), causing your computer to slow or outright freeze. So, what if you are asking for TONS of data? There are 3 main functions that allow you to search, (optionally) download, and then lazily load the data.

What does it mean to “lazily load the data?” A connection is established to the data files (either pointed at a local download or the files in the cloud) using DuckDB. Data are not read into memory until explicitly requested using dplyr::collect() or similar. We will show a few examples of how the data can be explored with this connection without needing to load the entire data set into memory.

Search -> Open Lazy Tibble

The function search_stac lets us search the STAC. Available arguments are similar to those found in read_waterdata_monitoring_location. In this example, we’re querying for all the daily STAC data available for Dane County, Wisconsin:

features_county <- search_stac(
    county_name = "Dane County",
    state_name = "Wisconsin",
    site_type = "Stream",
    collections = "daily"
)

The result of this function is a list with all the information that the next set of functions need to access the raw STAC files.

You might notice that the filtering arguments in the search_stac function are based only on the site information, not the data that the site has collected. If you want to narrow down the sites based on the type of data they have, use the original read_waterdata_combined_meta. For example, the “features_county” object above returned 67 sites in Dane County, WI that were considered “Stream” sites. But those sites could have any kind of data, and maybe we only want daily orthophosphate (parameter_code = “00671”). We can reduce the number of sites from 67 to 11 by starting with the read_waterdata_combined_meta function:

just_ortho <- read_waterdata_combined_meta(
    county_name = "Dane County",
    state_name = "Wisconsin",
    site_type = "Stream",
    data_type = "Daily values",
    parameter_code = "00671"
)

ortho_stac <- search_stac(
  monitoring_location_id = unique(just_ortho$monitoring_location_id),
  collections = "daily"
)

Next, we can use that list to create a lazy connection to the data in the cloud with the open_stac_parquet function. First, we need to create a connection. The function initial_connection establishes a generic DuckDB connection and adds your STAC_USGS_PAT token to the request headers. It is important to remember to close your connection when you are done using DBI::dbDisconnect. The open_stac_parquet call points this connection to the specific parquet files returned by search_stac.

con_1 <- initial_connection()

data_tbl <- open_stac_parquet(features = features_county,
                      con = con_1)

data_tbl is now a “lazy tibble”. This means you can use it as an input of any dplyr type commands. The full query is not sent until you dplyr::collect() the data. Before you run dplyr::collect, you can get some interesting information from the lazy tibble, all without loading the full dataset into memory. For example, showing the first 10 rows works the same as with a local tibble:

data_tbl
# A query:  ?? x 10
# Database: DuckDB 2.0.0 [Windows 10 x64:R 4.6.1/:memory:]
   time_series_id            monitoring_location_id parameter_code
   <chr>                     <chr>                  <chr>         
 1 5f9940b7927840d3ac520226… USGS-430639089185701   00045         
 2 5f9940b7927840d3ac520226… USGS-430639089185701   00045         
 3 5f9940b7927840d3ac520226… USGS-430639089185701   00045         
 4 5f9940b7927840d3ac520226… USGS-430639089185701   00045         
...   
# ℹ more rows
# ℹ 7 more variables: statistic_id <chr>, time <date>,
#   value <chr>, unit_of_measure <chr>, approval_status <chr>,
#   qualifier <list>, last_modified <dttm>
# ℹ Use `print(n = ...)` to see more rows
data_tbl |> 
  dplyr::summarise(
    min_date = min(time, na.rm = TRUE),
    mean_val = mean(as.numeric(value), na.rm = TRUE),
    count = dplyr::n(),
    .by = c(monitoring_location_id, parameter_code) 
  )
# A query:  ?? x 5
# Database: DuckDB 2.0.0 [Windows 10 x64:R 4.6.1/:memory:]
   monitoring_location_id parameter_code min_date   mean_val count
   <chr>                  <chr>          <date>        <dbl> <dbl>
 1 USGS-05427850          00060          2001-12-27  85.2     9097
 2 USGS-05427850          00665          2008-10-01   0.0919  6207
 3 USGS-05428600          00010          2017-11-03   5.18     621
 4 USGS-05406479          00300          2009-10-02  11.0     9137
...
# ℹ more rows
# ℹ Use `print(n = ...)` to see more rows

The ?? x 10 in the first row of output indicates the full data set was not loaded into memory, despite looking similar to the output of a regular R tibble. That demonstrates the memory efficiency – we don’t need to scan the whole data set just to read the first 10 rows or compute grouped summaries.

If we want to perform that entire summary and load the summary into memory:

data_summary <- data_tbl |> 
  dplyr::summarise(
    min_date = min(time, na.rm = TRUE),
    mean_val = mean(as.numeric(value), na.rm = TRUE),
    count = dplyr::n(),
    .by = c(monitoring_location_id, parameter_code) 
  ) |> 
  dplyr::collect()

If you needed a subset of the data:

df_subset <- data_tbl |> 
  dplyr::filter(
    monitoring_location_id %in% c("USGS-05427945",
                                  "USGS-05406483")
  ) |> 
  dplyr::collect()

Or, if you were confident that your computer could load all the data into R:

df <- data_tbl |> dplyr::collect()

Note that once you collect your desired data and it is loaded into memory, it becomes a regular, non-lazy tibble that is subject to the limitations of your computer set up.

There are many cool things to explore with a lazy tibble. Once you are done with your analysis, close the connection:

DBI::dbDisconnect(con_1)

Search -> Download

The workflow above hit the data in the cloud - and every time you explored the data, some-to-many requests are generated. There are a variety of reasons you would prefer to have your data local. You can use the function download_stac to copy all of the STAC files from the search_stac function.

You can choose to have the files downloaded into a Hive-partitioned format (download_structure = “hive”), or have the files downloaded to a single folder based on the collection type (download_structure = “collection_folder”).

Hive-partitioned download

Using download_structure = "hive", the files are downloaded in a Hive-partitioned set of parquet files. The partitioning is done by monitoring_location_id.

Let’s download all the continuous data that is available in the New York City area:

features_nyc <- search_stac(
    county_name = c("New York County",
                    "Kings County",
                    "Queens County",
                    "Bronx County",
                    "Richmond County"),
    state_name = "New York",
    collections = "continuous"
)

dir.create("nyc", showWarnings = FALSE)

download_path <- download_stac(
  features = features_nyc,
  file_directory = "nyc", 
  output_returned = "directory", 
  download_structure = "hive"
)

download_path
#> "nyc/continuous"

Inside the download folder, there is one subfolder per collection (“continuous” in this case). Within that, each monitoring location gets its own monitoring_location_id=<id> folder holding that site’s parquet file(s). This is the Hive-partitioning layout, where the folder names carry the partition key and value:

nyc/
└── continuous/
    ├── monitoring_location_id=USGS-01302020/
    │   └── historical.parquet
    ├── monitoring_location_id=USGS-01372043/
    │   ├── historical.parquet
    │   └── current.parquet
    ├── monitoring_location_id=USGS-01376307/
    │   └── historical.parquet
    └── ...

If you download more than one collection (for example collections = c("daily", "continuous")), each collection gets its own sibling folder:

nyc/
├── continuous/
│   ├── monitoring_location_id=USGS-01302020/
│   │   └── historical.parquet
│   └── ...
└── daily/
    ├── monitoring_location_id=USGS-01302020/
    │   └── data.parquet
    └── ...

Why create Hive-partitioned folders for each monitoring location’s data? It saves time and computing power the next time you access your downloaded data by monitoring location. Because the partition key is encoded in the folder names, DuckDB (and Arrow) can efficiently skip folders that don’t match a filter on monitoring_location_id, so only the relevant files are read.

Collection folder download

If instead you choose download_structure = "collection_folder", the files are saved in a single subfolder of file_directory. The subfolder’s name is the collection. There are no monitoring_location_id=<id> folders. Instead, each file name starts with the asset name and ends with the feature id, so every site’s files sit side by side.

Here we download the same New York City continuous data with a flat structure:

dir.create("nyc_collection", showWarnings = FALSE)

download_path_flat <- download_stac(
  features = features_nyc,
  file_directory = "nyc_collection", 
  output_returned = "directory", 
  download_structure = "collection_folder"
)

download_path_flat
#> "nyc_collection/continuous"

The files are named <asset>_<feature id>.parquet:

nyc_collection/
└── continuous/
    ├── historical_USGS-01302020.parquet
    ├── historical_USGS-01372043.parquet
    ├── current_USGS-01372043.parquet
    ├── historical_USGS-01376307.parquet
    └── ...

If you download more than one collection, each collection still gets its own sibling folder:

nyc_collection/
├── continuous/
│   ├── historical_USGS-01302020.parquet
│   └── ...
└── daily/
    ├── data_USGS-01302020.parquet
    └── ...

To get the path of every individual file instead of the folder, use output_returned = "files":

files_flat <- download_stac(
  features = features_nyc,
  file_directory = "nyc_collection", 
  output_returned = "files", 
  download_structure = "collection_folder",
  showWarnings = FALSE
)

head(files_flat, 3)
#> [1] "nyc_collection/continuous/historical_USGS-01302020.parquet"
#> [2] "nyc_collection/continuous/historical_USGS-01372043.parquet"
#> [3] "nyc_collection/continuous/current_USGS-01372043.parquet"

The flat structure is a good fit if you want to work with a specific set of files (for example, in a targets workflow where each file is its own target), or if you just want all of the data from a collection in one place. Because monitoring_location_id is not encoded in the folder names, DuckDB and Arrow can’t skip files based on a monitoring_location_id filter. They have to open every file and filter on the monitoring_location_id column inside it. If you plan to repeatedly query individual sites from a large download, the Hive-partitioned structure is the better choice.

You can open a collection folder the same way as a Hive-partitioned folder. The monitoring_location_id column is stored inside each file, so it is available either way:

con_flat <- initial_connection()

nyc_flat_tbl <- open_stac_parquet(
  features = download_path_flat,
  con = con_flat
)

DBI::dbDisconnect(con_flat)

When opening a flat folder with Arrow, there is no partition key in the folder names to parse, so you don’t need the partitioning argument: arrow::open_dataset("nyc_collection/continuous", format = "parquet").

Lazy Tibble

The open_stac_parquet function works the same way on local files as it does on the cloud files shown earlier. Instead of the list returned by search_stac, pass it the path returned by download_stac. Nothing is loaded into memory until you call dplyr::collect().

con_nyc <- initial_connection()

nyc_tbl <- open_stac_parquet(
  features = download_path,
  con = con_nyc
)

nyc_tbl
# A query:  ?? x 11
# Database: DuckDB 2.0.0 [Windows 10 x64:R 4.6.1/:memory:]
   time_series_id   monitoring_location_id parameter_code statistic_id
   <chr>            <chr>                  <chr>          <chr>       
 1 dafdaa4075e34bc… USGS-01302020          00065          00011       
 2 a394ba8aa6d1441… USGS-01302020          63680          00011       
 3 c946acb1602d4ef… USGS-01302020          00010          00011       
 4 254fc69aca7c437… USGS-01302020          90860          00011       
...
# ℹ more rows
# ℹ 7 more variables: time <dttm>, value <chr>,
#   unit_of_measure <chr>, approval_status <chr>, qualifier <list>,
#   last_modified <dttm>, method_category <chr>
# ℹ Use `print(n = ...)` to see more rows

Use dplyr verbs to filter and summarize. The query runs in DuckDB against the local parquet files:

nyc_summary <- nyc_tbl |>
  dplyr::filter(
    monitoring_location_id == "USGS-01302020",
    parameter_code == "00060"
  ) |>
  dplyr::mutate(value = as.numeric(value)) |>
  dplyr::summarise(
    min_val = min(value, na.rm = TRUE),
    mean_val = mean(value, na.rm = TRUE),
    max_val = max(value, na.rm = TRUE),
    count = dplyr::n()
  ) |>
  dplyr::collect()

To bring a subset into R as a data frame:

df_site <- nyc_tbl |>
  dplyr::filter(
    monitoring_location_id == "USGS-01302020",
    parameter_code == "00060"
  ) |>
  dplyr::collect()

Close the connection when you are done:

DBI::dbDisconnect(con_nyc)

Multiple Collections Caveat

It is important to know that if you had downloaded more than one collection, you need to specify a path to the specific collection for the input of open_stac_parquet. Here’s an example of exploring just the daily data, even if you downloaded daily and continuous:

features_county <- search_stac(
    county_name = "Dane County",
    state_name = "Wisconsin",
    site_type = "Stream",
    collections = c("daily", "continuous")
)

dir.create("Dane", showWarnings = FALSE)

partition_output <- download_stac(features = features_county,
                                  file_directory = "Dane", 
                                  output_returned = "directory")

partition_output
#> "Dane/continuous" "Dane/daily"

con_dane <- initial_connection()

dane_tbl <- open_stac_parquet(
  features = "Dane/daily", #or partition_output[2]
  con = con_dane
)

dane_tbl

DBI::dbDisconnect(con_dane)
# A query:  ?? x 10
# Database: DuckDB 2.0.0 [Windows 10 x64:R 4.6.1/:memory:]
   time_series_id  monitoring_location_id parameter_code statistic_id time      
   <chr>           <chr>                  <chr>          <chr>        <date>    
 1 50f4289d95f846… USGS-05406000          00060          00003        1946-01-01
 2 50f4289d95f846… USGS-05406000          00060          00003        1946-01-02
 3 50f4289d95f846… USGS-05406000          00060          00003        1946-01-03
 4 50f4289d95f846… USGS-05406000          00060          00003        1946-01-04
...
# ℹ more rows
# ℹ 5 more variables: value <chr>, unit_of_measure <chr>,
#   approval_status <chr>, qualifier <list>, last_modified <dttm>
# ℹ Use `print(n = ...)` to see more rows

DuckDB SQL

If you prefer SQL to dplyr, you can send raw SQL strings to DuckDB with DBI::dbGetQuery (returns a data frame) and DBI::dbExecute (runs a statement and returns the number of affected rows). DuckDB’s read_parquet function reads the downloaded files directly, and the ** wildcard matches every partition folder. Let’s calculate the total number of rows summed across all of our continuous parquet files.

con_sql <- initial_connection()

# Count the rows in the downloaded files:
DBI::dbGetQuery(
  con_sql,
  "SELECT COUNT(*) AS n_rows
   FROM read_parquet('nyc/continuous/**/*.parquet')"
)
    n_rows
1 22456339

A summary by site and parameter code, computed in DuckDB. Only the summary table is loaded into R:

sql_summary <- DBI::dbGetQuery(
  con_sql,
  "SELECT
     monitoring_location_id,
     parameter_code,
     MIN(time) AS start_time,
     MAX(time) AS end_time,
     COUNT(*) AS n_obs,
     AVG(TRY_CAST(value AS DOUBLE)) AS mean_val
   FROM read_parquet('nyc/continuous/**/*.parquet')
   GROUP BY monitoring_location_id, parameter_code
   ORDER BY monitoring_location_id, parameter_code"
)
head(sql_summary, 3)
  monitoring_location_id parameter_code          start_time            end_time
1          USGS-01302020          00010 2021-06-28 16:45:00 2026-12-01 04:30:00
2          USGS-01302020          00060 2007-10-01 05:00:00 2026-12-01 04:30:00
3          USGS-01302020          00065 2007-10-01 05:00:00 2026-12-01 04:30:00
   n_obs   mean_val
1 186147 13.7268691
2 666049 74.6325464
3 668355  0.7805187

value is stored as text, so TRY_CAST(value AS DOUBLE) converts it and returns NULL for anything that can’t be converted. To pass values into a query safely, use ? placeholders and the params argument rather than pasting strings together:

df_site <- DBI::dbGetQuery(
  con_sql,
  "SELECT *
   FROM read_parquet('nyc/continuous/**/*.parquet')
   WHERE monitoring_location_id = ?
     AND parameter_code = ?",
  params = list("USGS-01302020", "00060")
)
head(df_site, 3)
                    time_series_id monitoring_location_id parameter_code
1 7c1f90fe567b4cdaa6ddd76127ae4140          USGS-01302020          00060
2 7c1f90fe567b4cdaa6ddd76127ae4140          USGS-01302020          00060
3 7c1f90fe567b4cdaa6ddd76127ae4140          USGS-01302020          00060
  statistic_id                time value unit_of_measure approval_status qualifier
1        00011 2026-07-04 05:45:00  25.4          ft^3/s        Approved      NULL
2        00011 2026-07-04 06:00:00  25.4          ft^3/s        Approved      NULL
3        00011 2026-07-04 06:15:00  25.4          ft^3/s        Approved      NULL
        last_modified method_category
1 2026-11-09 17:33:11            <NA>
2 2026-11-09 17:33:11            <NA>
3 2026-11-09 17:33:11            <NA>

If you run several queries against the same files, create a view once and query it by name. dbExecute runs statements that don’t return rows:

DBI::dbExecute(
  con_sql,
  "CREATE OR REPLACE VIEW nyc_continuous AS
   SELECT * FROM read_parquet('nyc/continuous/**/*.parquet')"
)

DBI::dbGetQuery(
  con_sql,
  "SELECT parameter_code, COUNT(*) AS n_obs
   FROM nyc_continuous
   GROUP BY parameter_code
   ORDER BY n_obs DESC"
)
   parameter_code   n_obs
1           62611 5080265
2           62620 3251539
3           62610 3222729
4           62619 2505005
5           00060 1709626
6           00065 1511418
7           00010  925588
8           63680  900492
9           00095  805663
10          90860  805643
11          00400  510725
12          00300  486863
13          62615  277702
14          62614  221084
15          99409  179416
16          72137   31373
17          72019   31208

Close the connection when you are done:

DBI::dbDisconnect(con_sql)

Arrow

The arrow package can also open the partitioned folder. arrow::open_dataset reads the monitoring_location_id= folder names and adds monitoring_location_id as a column. Nothing is loaded into memory until you call dplyr::collect().

library(arrow)
library(dplyr)

# Point to the collection folder inside the download directory:
nyc_ds <- open_dataset(
  "nyc/continuous",
  format = "parquet",
  partitioning = hive_partition(monitoring_location_id = large_utf8())
)

nyc_ds
FileSystemDataset with 187 Parquet files
11 columns
time_series_id: large_string
monitoring_location_id: large_string
parameter_code: large_string
statistic_id: large_string
time: timestamp[us, tz=UTC]
value: large_string
unit_of_measure: large_string
approval_status: large_string
qualifier: list<element: string>
last_modified: timestamp[us, tz=UTC]
method_category: large_string

The parquet files already store monitoring_location_id as a large_string. By default, arrow reads the same value from the folder name as a regular string, and the two types can’t be merged. That produces the error Field monitoring_location_id has incompatible types: large_string vs string. Declaring the partition field as large_utf8() makes the two types match.

Use dplyr verbs on the dataset to filter and summarize. The filter on monitoring_location_id is applied to the folder names, so only the matching files are read:

nyc_summary <- nyc_ds |>
  dplyr::mutate(value = as.numeric(value)) |>
  dplyr::summarise(
    min_val = min(value, na.rm = TRUE),
    mean_val = mean(value, na.rm = TRUE),
    max_val = max(value, na.rm = TRUE),
    count = dplyr::n(),
    .by = c(monitoring_location_id, parameter_code)
  ) |>
  dplyr::collect()

To bring a subset into R as a data frame:

df_site <- nyc_ds |>
  dplyr::filter(
    monitoring_location_id == "USGS-01302020",
    parameter_code == "00060"
  ) |>
  dplyr::collect()

Further Considerations

Understanding output_returned

The argument output_returned can be either “directory” or “files”. Setting output_returned = "directory" will return a path to the folder where each collection’s data is stored. In this example, we see the difference between “directory” or “files”:

features_county <- search_stac(
    county_name = "Dane County",
    state_name = "Wisconsin",
    site_type = "Stream",
    collections = "daily"
)

dir.create("Dane", showWarnings = FALSE)

partition_output <- download_stac(features = features_county,
                                  file_directory = "Dane", 
                                  output_returned = "directory")

partition_output
#> "Dane/daily"

files_output <- download_stac(features = features_county,
                              file_directory = "Dane", 
                              output_returned = "files")

files_output
#> [1] "Dane/daily/monitoring_location_id=USGS-05406497/data.parquet"                  
#> [2] "Dane/daily/monitoring_location_id=USGS-05406476/data.parquet" 
#> [3] "Dane/daily/monitoring_location_id=USGS-05406483/data.parquet"
#> ....etc....

⚠️ If you download some data, and then later download more data, the data loaded from the “directory” will include all the data from both downloads.

monitoring_location_id <- c("USGS-01435000", "USGS-05406360")

features <- search_stac(
    monitoring_location_id = monitoring_location_id,
    collections = c("daily"))

dir.create("specific_sites", showWarnings = FALSE)

local_path <- download_stac(
  features = features,
  file_directory = "specific_sites", 
  output_returned = "directory")

more_features <- search_stac(
    monitoring_location_id = c("USGS-05429120", "USGS-05406457"),
    collections = c("daily"))

more_local_path <- download_stac(
  features = more_features,
  file_directory = "specific_sites", 
  output_returned = "directory")

local_path
#> [1] "specific_sites/daily"
more_local_path
#> [1] "specific_sites/daily"

con <- initial_connection()

site_tbl <- open_stac_parquet(
  features = more_local_path,
  con = con
)

# So even though we input `more_local_path`, 
# we see all 4 sites from both `local_path` and `more_local_path`
site_tbl |> dplyr::pull(monitoring_location_id) |> unique()
#> [1] "USGS-01435000" "USGS-05406360" "USGS-05406457" "USGS-05429120"

DBI::dbDisconnect(con)

 

That means you cannot use the “partition_folder” output to get just the data from more_features. You will see the following warning if you do that:

Warning message:
In download_stac(features = more_features, file_directory = "specific_sites") :
  Files already exist within: specific_sites/daily

You can however use the “files” output to do that:


monitoring_location_id <- c("USGS-01435000", "USGS-05406360")

features <- search_stac(
    monitoring_location_id = monitoring_location_id,
    collections = c("daily"))

dir.create("specific_sites_2", showWarnings = FALSE)

local_path <- download_stac(
  features = features,
  file_directory = "specific_sites_2", 
  output_returned = "files")

more_features <- search_stac(
    monitoring_location_id = c("USGS-05429120", "USGS-05406457"),
    collections = c("daily"))

more_local_path <- download_stac(
  features = more_features,
  file_directory = "specific_sites_2", 
  output_returned = "files")

local_path
#> [1] "specific_sites_2/daily/monitoring_location_id=USGS-05406360/data.parquet"
#> [2] "specific_sites_2/daily/monitoring_location_id=USGS-01435000/data.parquet"
more_local_path
#> [1] "specific_sites_2/daily/monitoring_location_id=USGS-05406457/data.parquet"
#> [2] "specific_sites_2/daily/monitoring_location_id=USGS-05429120/data.parquet"

con <- initial_connection()

site_tbl <- open_stac_parquet(
  features = more_local_path,
  con = con
)

# Now since we used the "targets" output, using `more_local_path`
# only gives us the sites that were requested in `more_features`
site_tbl |> dplyr::pull(monitoring_location_id) |> unique()
#> [1] "USGS-05406457" "USGS-05429120"

DBI::dbDisconnect(con)

Updating “Current” Continuous Data

Each continuous feature has two assets: “historical” (everything older than approximately 150 days) and “current” (approximately the last 150 days). The “current” file is the one that gets refreshed often. The “historical” file changes much less. If you already have a local copy of the continuous data, you can refresh only the “current” files and leave the “historical” files as they are.

download_stac saves each asset in the site’s partition folder, named after the asset. After a full download, a site looks like this:

nyc/
└── continuous/
    └── monitoring_location_id=USGS-01302020/
        ├── current.parquet
        └── historical.parquet

To update only the “current” files, keep only the “current” asset in each feature before downloading. download_stac downloads whatever assets are in the features it is given, so we need to do a little filtering to make sure historical.parquet is not requested or overwritten:

features_nyc <- search_stac(
    county_name = c("New York County",
                    "Kings County",
                    "Queens County",
                    "Bronx County",
                    "Richmond County"),
    state_name = "New York",
    collections = "continuous"
)

# Keep only the "current" asset for each feature:
features_current <- lapply(features_nyc, function(f) {
  keep <- intersect("current", names(f[["assets"]]))
  f[["assets"]] <- f[["assets"]][keep]
  f
})

download_path <- download_stac(
  features = features_current,
  file_directory = "nyc",
  output_returned = "directory",
  showWarnings = FALSE # we expect the folder to already exist
)

Since overwrite = TRUE is the default, the existing current.parquet files are replaced and the historical.parquet files are untouched. To confirm, you can check when each file was last modified:

files <- list.files(
  "nyc/continuous",
  pattern = "\\.parquet$",
  recursive = TRUE,
  full.names = TRUE
)

file.info(files)[, c("size", "mtime")]
                                    size   mtime
USGS-01302020/current.parquet       77978  2026-11-30 10:53:07
USGS-01302020/historical.parquet   240157  2026-11-25 15:16:42
...

The “current” and “historical” data can overlap, so the same time_series_id and time may appear in both files. When you read the data, fix_continuous_overlap keeps the row with the most recent last_modified:

con <- initial_connection()

nyc_tbl <- open_stac_parquet(
  features = download_path,
  con = con
)

df_site <- nyc_tbl |>
  dplyr::filter(
    monitoring_location_id == "USGS-01302020",
    parameter_code == "00060"
  ) |>
  dplyr::collect() |>
  fix_continuous_overlap()

DBI::dbDisconnect(con)
range(df_site$time)
[1] "2007-10-01 05:00:00 UTC" "2026-12-01 04:30:00 UTC"

Over time, data moves from “current” to “historical”. If you only refresh “current”, the local historical.parquet gets out of date, and a gap opens up once the data you have in “historical” ends more than approximately 150 days ago. Re-download the full set of assets (using the original features_nyc) every so often to close that gap.

Re-partition Examples

The sweet spot of Hive-partitioning is 100MB-1GB per individual parquet file. Too big or too little of files cause different kinds of bottlenecks. The individual monitoring_location_id files that come from the STAC service are almost universally smaller than this. Here is an example of how to take the monitoring_location_id partitioning, and re-partition it to state_name.

library(duckdb)
library(dplyr)
library(dataRetrieval)

con_1 <- initial_connection()

sites <- read_waterdata_combined_meta(
  state_name = c("Alaska", "Wisconsin"),
  parameter_code = "00060",
  statistic_id = "00003",
  skipGeometry = TRUE
)

site_features <- search_stac(
  monitoring_location_id = unique(sites$monitoring_location_id),
  collections = "daily"
)

dir.create("pqts", showWarnings = FALSE)

# Default is partitioned folder:
dwnlwd <- download_stac(
  site_features,
  file_directory = here::here("pqts"),
  overwrite = FALSE
)

con_1 <- initial_connection() 

# By default, duckdb will go up to 80% of system RAM
# If you want to change that, you can do it like this:
# dbExecute(con_1, "SET memory_limit = '1GB';")
# My regular laptop has 32GB installed RAM

register_data <- open_stac_parquet(features = dwnlwd, 
                      con = con_1) |> 
  filter(time_series_id %in% sites$combined_meta_id) |> 
  left_join(sites |> 
              select(monitoring_location_id, state_name),
            by = "monitoring_location_id", 
#copy = "inline" is OK if sites df is smallish, 
# if it's bigger use copy = "temp-table":
            copy = "inline") |>
  duckdb::duckdb_register(conn = con_1, name = "state_partitions")

dir.create("state_discharge", showWarnings = FALSE)

DBI::dbExecute(con_1, dplyr::sql("COPY (
    SELECT *
    FROM state_partitions
  ) TO 'state_discharge' (FORMAT PARQUET, PARTITION_BY (state_name))
")) 

duckdb::duckdb_unregister(con_1, "state_partitions")
DBI::dbDisconnect(con_1, shutdown = TRUE)

Take time to think about how you plan to access/analyze your large data sets, and use that information to re-partition the data to maximize efficiency.

If you pull a LOT of data, eventually even this workflow will exceed memory limits even using DuckDB or Arrow. The example above gave the error “Out of Memory Error: Allocation failure” when run with continuous data. Splitting the re-partitioning into more manageable chunks or other techniques will be needed in those situations.

targets Workflow

You can also use these functions in a targets workflow. Here is an example of a _targets.R file that could be used. In this example, we first find all the daily mean discharge in Alaska. In the download_stac function, we then set the argument output_returned = "files", the result of that function will be a vector for the full path for all of the downloaded files. Finally, the last target “modeled_data” creates a dynamic branch for each downloaded file. In this very simple example, we run a linear regression to demonstrate how a targets workflow might be used to model a large batch of data:

library(targets)
library(tarchetypes)

tar_option_set(
  packages = c(
    "tidyverse",
    "dataRetrieval",
    "here"
  )
)

model_data <- function(x) {
  df <- arrow::read_parquet(x)
  discharge <- df |>
    dplyr::filter(
      parameter_code == "00060",
      statistic_id == "00003"
    )
  model_out <- lm(data = discharge, formula = value ~ time)
  
  slope <- coef(model_out)[["time"]]
  return(slope)
}


dir.create("pqts", showWarnings = FALSE)

list(
  tar_target(
    name = sites,
    command = read_waterdata_combined_meta(
      state_name = "Alaska",
      parameter_code = "00060",
      statistic_id = "00003",
      skipGeometry = TRUE
    )
  ),
  tar_target(
    name = site_features,
    command = search_stac(
      monitoring_location_id = unique(sites$monitoring_location_id),
      collections = "daily"
    )
  ),
  tar_target(
    name = dwnlwd,
    command = download_stac(
      site_features,
      file_directory = here("pqts"),
      output_returned = "files"
    )
  ),
  # A dynamic branch based on the individual files in dwnlwd
  # In this example, a model is run on each individual file:
  tar_target(
    modeled_data,
    model_data(x = dwnlwd),
    pattern = map(dwnlwd),
    iteration = "vector"
  )
)