Type: Package
Title: Query the 'Google Trends for Health' API
Version: 1.0.0
Maintainer: Oscar de Leon <odeleon@emory.edu>
Description: Connects to the 'Google Trends for Health' API hosted at https://trends.google.com/trends/, allowing projects authorized to use the health research data to query 'Google Trends'.
License: MIT + file LICENSE
URL: https://github.com/CDCgov/gtrendshealth
Imports: utils, jsonlite, httr
Encoding: UTF-8
RoxygenNote: 7.3.2
Depends: R (≥ 4.1.0)
Suggests: testthat (≥ 3.0.0)
Config/testthat/edition: 3
BugReports: https://github.com/CDCgov/gtrendshealth/issues
NeedsCompilation: no
Packaged: 2025-06-14 01:20:06 UTC; oscar
Author: Oscar de Leon ORCID iD [aut, cre], US Centers for Disease Control and Prevention [cph]
Repository: CRAN
Date/Publication: 2025-06-17 06:10:02 UTC

gtrendshealth: Query the 'Google Trends for Health' API

Description

Connects to the 'Google Trends for Health' API hosted at https://trends.google.com/trends/, allowing projects authorized to use the health research data to query 'Google Trends'.

Author(s)

Maintainer: Oscar de Leon odeleon@emory.edu (ORCID)

Other contributors:

See Also

Useful links:


Read the GOOGLE TRENDS FOR HEALTH API Key

Description

This function will read your GOOGLE TRENDS FOR HEALTH API key from the environment variables. If you do not have an .Renviron file, the function will create one for you. If you already have an .Renviron file, the function will append the key to your existing file, while making a backup of your original file for recovery purposes.

Usage

get_gt_api_key(key = NULL)

Arguments

key

The API key from your Google Developer project authorized for Google Trends for Health API use, formatted in quotes. A key can be acquired by requesting access at https://support.google.com/trends/contact/trends_api and following the setup instructions.

Value

Returns the API key that is set in the GOOGLE_TRENDS_FOR_HEALTH_API_KEY environment variable.

Examples


tryCatch(
  get_gt_api_key(),
  error = function(e) cat("You need to set up a valid key")
)


Description

For health research only, fetches a graph of search volumes per time within a set of restrictions. Each term will result in a timeline of search over time. Note the data is sampled and Google can't guarantee the accuracy of the numbers. This service is closed to a subset of Health researchers. The quota provision is individually maintained by the Trends team.

Usage

get_health_trends(
  terms,
  resolution,
  start,
  end,
  country = NULL,
  region = NULL,
  dma = NULL,
  key = get_gt_api_key(),
  wait = TRUE
)

Arguments

terms

Required. Search terms the user wishes to explore. Up to 30 queries can be sent. Term format can be either a query or entity (e.g. /m/0d2p9p) and can include ORs using '+' sign. Example: "/m/0d2p9p + /m/0nd4ffr + awesomeness" will return a combined timeline of the three terms (which obviously differs from "/m/0d2p9p, /m/0nd4ffr, awesomeness" that returns 3 different timelines.)

resolution

One of day, week, month, or year. Week is default for the API, but required here to protect the quotas.

start

A date object representing the start of the query period. The default for the API is 2004-01-01, but a value is required here.

end

A date object representing the start of the query period. The default for the API is today, but a value is required here.

country, region, dma

Only one field of GeoRestriction should be filled. Country format is ISO-3166-2 (2-letters), e.g. US. Region format is ISO-3166-2 (4-letters), e.g. US-NY (see more examples here: en.wikipedia.org/wiki/ISO_3166-2:US). DMA is nielsen dma id, e.g. 501 (support.google.com/richmedia/answer/2745487).

key

The API key from your Google Developer project authorized for Google Trends for Health API use, as a character. Defaults to using the API key set up for this package, if any. A key can be acquired by requesting access at https://support.google.com/trends/contact/trends_api and following the setup instructions.

wait

Wait before submitting the query, to protect the API quotas. The Google Trends for Gealth API is limited to 2 queries per second.

Value

A data.frame with one row per term and period, with the probability of the term being included in a search, for the specified geographic restriction and dates range. The probabilities are provided by the API as values multiplied by 1e7.

Examples


if(Sys.getenv("GOOGLE_TRENDS_FOR_HEALTH_API_KEY")==""){
  # Set up your API if not installed
  set_gt_api_key("<your-valid-api-key>")
}

# run this example if you have set up a valid API key
tryCatch({
  # Query the Google Trends for Health service
  monthly_trends <- get_health_trends(
    terms = "fever",
    resolution = "month",
    start = as.Date("2024-01-01"),
    end = as.Date("2024-12-31"),
    country = "US"
  )

  # set a date for each monthly observation
  # using the 15th of each month for the day
  monthly_trends$date <- as.Date(
    strptime(
      paste("15", monthly_trends$period),
       format = "%d %b %Y"
    )
  )

  print(monthly_trends)

  # Query the Google Trends for Health service
  daily_trends <- get_health_trends(
    terms = "fever",
    resolution = "day",
    start = as.Date("2024-01-01"),
    end = as.Date("2024-12-31"),
    country = "US"
  )

  head(daily_trends)

  # plot the time series
  plot(
    daily_trends$date, daily_trends$value, type = "l", col = "blue",
    xlab = "Date",
    ylab = "Value",
    main = "Daily and Monthly Trends for Fever"
  )
  lines(monthly_trends$date, monthly_trends$value, col = "red", lwd = 2)
  legend("topright", legend = c("Daily Trends", "Monthly Trends"),
    col = c("blue", "red"), lty = 1, lwd = c(1, 2))
}, error = function(e) cat("\nYou need to set up a valid API key")
)


Verify provided path

Description

Verify path availability.

Usage

gt_verify_path(path)

Arguments

path

Path to verify.


Delete a saved GOOGLE TRENDS FOR HEALTH API Key

Description

This function will uninstall your GOOGLE TRENDS FOR HEALTH API key from the environment variables. If a path is provided, it will be used to remove the key from .Renviron file in that path.

Usage

remove_gt_api_key(remove = FALSE, path = NULL)

Arguments

remove

Whether to remove the key.

path

Path to look for an .Renviron file.


Set up a GOOGLE TRENDS FOR HEALTH API Key for Repeated Use

Description

This function will set your GOOGLE TRENDS FOR HEALTH API key as an environment variable. If using install = TRUE then the key will also be saved to your .Renviron file so it can be called securely without being stored in your code. After you have installed your key, it can be called any time by typing Sys.getenv("GOOGLE_TRENDS_FOR_HEALTH_API_KEY") and can be used in package functions by simply typing GOOGLE_TRENDS_FOR_HEALTH_API_KEY If you do not have an .Renviron file, the function will create one for you. If you already have an .Renviron file, the function will append the key to your existing file, while making a backup of your original file for recovery purposes.

Usage

set_gt_api_key(key, overwrite = FALSE, install = FALSE, path = "HOME")

Arguments

key

The API key from your Google Developer project authorized for Google Trends for Health API use, formatted in quotes. A key can be acquired by requesting access at https://support.google.com/trends/contact/trends_api and following the setup instructions.

overwrite

If this is set to TRUE, it will overwrite an existing CENSUS_API_KEY that you already have in your .Renviron file.

install

if TRUE, will install the key in your .Renviron file for use in future sessions. Defaults to FALSE.

path

Path to install the API key into.

Value

Returns the API key that was saved to the GOOGLE_TRENDS_FOR_HEALTH_API_KEY environment variable. If install = TRUE, it saves the API key in the specified .Renviron file.

Examples


set_gt_api_key("111111abc", install = TRUE, path = tempdir())
# The first time, reload your environment so you can use the key without
# restarting R.
readRenviron("~/.Renviron")
# You can check it with:
Sys.getenv("GOOGLE_TRENDS_FOR_HEALTH_API_KEY")

# If you need to overwrite an existing key:
set_gt_api_key(
  "111111abc", overwrite = TRUE, install = TRUE, path = tempdir()
)
# The first time, reload your environment so you can use the key without
# restarting R.
readRenviron("~/.Renviron")
# You can check it with:
Sys.getenv("GOOGLE_TRENDS_FOR_HEALTH_API_KEY")

# clean up
unlink(
list.files(tempdir(), all.files = TRUE, full.names = TRUE, pattern = ".Renv")
)