if(Sys.getenv("GOOGLE_TRENDS_FOR_HEALTH_API_KEY")==""){
# Set up your API if not installed
set_gt_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")
)
Run the code above in your browser using DataLab