Skip to content

Commit

Permalink
Carbon Dioxide functions
Browse files Browse the repository at this point in the history
  • Loading branch information
Hernando committed Aug 2, 2020
1 parent 6cb9a59 commit 047f798
Show file tree
Hide file tree
Showing 12 changed files with 243 additions and 12 deletions.
4 changes: 2 additions & 2 deletions DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ Authors@R:
role = c("aut", "cre"),
email = "[email protected]",
comment = c(ORCID = "0000-0001-6790-4870"))
Description: The goal of hockeystick is to download and visualize essential climate change data.
Description: The hockeystick package provides access to essential climate change datasets. The package includes functions to download and visualize atmospheric carbon dioxide.
License: MIT + file LICENSE
Encoding: UTF-8
LazyData: true
Roxygen: list(markdown = TRUE)
RoxygenNote: 7.1.1
URL: https://github.com/cortinah/hockeystick
BugReports: https://github.com/cortinah/hockeystick/issues
Imports: rappdirs
Imports: ggplot2, lubridate, rappdirs, readr
Suggests:
spelling
Language: en-US
7 changes: 7 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
# Generated by roxygen2: do not edit by hand

S3method(print,hockeystick_cache_info)
export(get_carbon)
export(hockeystick_cache_delete)
export(hockeystick_cache_delete_all)
export(hockeystick_cache_details)
export(hockeystick_cache_list)
export(plot_carbon)
import(ggplot2)
importFrom(lubridate,ceiling_date)
importFrom(lubridate,ymd)
importFrom(readr,read_table2)
importFrom(utils,download.file)
109 changes: 109 additions & 0 deletions R/carbon.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
#' Download and plot essential climate data
#'
#' Retrieves atmospheric carbon dioxide measurements from National Oceanic and Atmospheric Administration
#' Earth System Research Laboratories monitoring laboratory in Mauna Loa, Hawaii.
#' \url{https://www.esrl.noaa.gov/gmd/ccgg/trends/data.html}
#'
#' @name get_carbon
#' @param use_cache (boolean) Return cached data if available, defaults to TRUE. Use FALSE to fetch updated data.
#'
#' @return Invisibly returns a tibble with the monthly carbon dioxide series
#'
#' @details `fetch_carbon` invisibly returns a tibble with NOAA's monthly average carbon dioxide measurement.
#' The returned object includes date, year, month, average, interpolated, and trend columns.
#' Average and interpolated are basically identical with interpolated filling in a very small number of missing months.
#' Trend is NOAA's published trend. Please refer to above website for details.
#'
#' @importFrom readr read_table2
#' @importFrom lubridate ymd ceiling_date
#' @importFrom utils download.file
#'
#' @examples
#' # Fetch from cache if available:
#' maunaloa <- get_carbon()
#' #
#' # Force cache refresh:
#' \dontrun{
#' maunaloa <- get_carbon(use_cache=FALSE)}
#' #
#' # Review cache contents and last update dates:
#' hockeystick_cache_details()
#' #
#' # Plot output using package's built-in ggplot2 settings
#' plot_carbon(maunaloa)
#'
#' @author Hernando Cortina, \email{hch@@alum.mit.edu}
#' @references
#' Dr. Pieter Tans, NOAA/GML \url{www.esrl.noaa.gov/gmd/ccgg/trends/} and Dr. Ralph Keeling, Scripps Institution of Oceanography \url{scrippsco2.ucsd.edu/}.
#'
#'
#' C.D. Keeling, R.B. Bacastow, A.E. Bainbridge, C.A. Ekdahl, P.R. Guenther, and L.S. Waterman, (1976), Atmospheric carbon dioxide variations at Mauna Loa Observatory, Hawaii, \emph{Tellus}, vol. 28, 538-551
#' @export
get_carbon <- function(use_cache = TRUE) {

hs_path <- rappdirs::user_cache_dir("hockeystick")

if (use_cache) {
if (file.exists(file.path(hs_path,'maunaloa.rds'))) return(invisible(readRDS((file.path(hs_path,'maunaloa.rds')))))
}

file_url <- 'ftp://aftp.cmdl.noaa.gov/products/trends/co2/co2_mm_mlo.txt'
dl <- tempfile()
download.file(file_url, dl)
maunaloa <- read_table2(dl, col_names = FALSE, skip = 72)
colnames(maunaloa) <- c('year', 'month', 'date', 'average', 'interpolated', 'trend','days')
maunaloa$date <- ceiling_date(ymd(paste(maunaloa$year, maunaloa$month, '01',sep='-')), unit='month')-1

dir.create(hs_path, showWarnings = FALSE, recursive = TRUE)
saveRDS(maunaloa, file.path(hs_path, 'maunaloa.rds'))

invisible(maunaloa)
}



#' Download and plot essential climate data
#'
#' Plots carbon dioxide data retrieved using `get_carbon()` with ggplot2. The output ggplot2 object may be modified.
#'
#'
#' @name plot_carbon
#' @param dataset Name of the tibble generated by `get_carbon`
#' @param print (boolean) Display carbon dioxide ggplot2 chart, defaults to TRUE. Use FALSE to not display chart.
#'
#' @return Invisibly returns a ggplot2 object with carbon dioxide chart
#'
#' @details `plot_carbon` invisibly returns a ggplot2 object with a pre-defined carbon dioxide chart using data from `get_carbon`.
#' By default the chart is also displayed. Users may further modify the output ggplot2 chart.
#'
#' @import ggplot2
#'
#' @examples
#' # Fetch carbon dioxide data:
#' maunaloa <- get_carbon()
#' #
#' # Plot output using package's built-in ggplot2 defaults
#' plot_carbon(maunaloa)
#'
#' # Or just call plot_carbon(), which defaults to use_carbon() dataset
#' plot_carbon()
#'
#' p <- plot_carbon(maunaloa, print = FALSE)
#' p + ggplot2::labs(title='The Keeling Curve')
#'
#' @author Hernando Cortina, \email{hch@@alum.mit.edu}
#'
#' @export

plot_carbon <- function(dataset = get_carbon(), print=TRUE) {

plot <- ggplot(dataset, aes(x=date, y=interpolated)) +geom_line(color='dodgerblue2', alpha=0.7) + theme_bw(base_size=12) +
scale_x_date(name=NULL, date_breaks='10 years', limits=c(ymd('1954-01-01'), ymd(paste0(max(dataset$year)+1,'-01-01'))), date_labels='%Y') +
scale_y_continuous(limits=c(300, round(max(dataset$average),-1)), breaks=seq(300, round(max(dataset$average),-1), 20)) +
geom_line(aes(y=trend), size=1, col='firebrick1') +
labs(title=expression('Atmospheric '*CO[2]*' (Keeling Curve)'), subtitle=expression('Mauna Loa '*CO[2]*' monthly mean ppm'),
y=expression(CO[2]*' concentration in air' ), caption='Source: NOAA/ESRL and Scripps Institution of Oceanography.\nhttps://www.esrl.noaa.gov/gmd/ccgg/trends/data.html')

if (print) print(plot)
invisible(plot)
}
2 changes: 2 additions & 0 deletions R/globalvars.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Setting global variables to avoid R CMD check notices
utils::globalVariables(c('interpolated', 'trend'))
12 changes: 7 additions & 5 deletions README.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,17 @@ You can install the development version of hockeystick from [https://github.com/
remotes::install_github("cortinah/hockeystick")
```

## Example
## Examples

This is a basic example which shows you how to solve a common problem:
Retrieve NOAA/ESRL Mauna Loa CO<sub>2</sub> concentration and plot it:

```{r example}
```{r example, out.width='75%', fig.retina=2}
library(hockeystick)
## basic example code
ml_co2 <- get_carbon()
plot_carbon(ml_co2)
```


## Acknowledgments
- Caching data sets: ROpenSci guide to [Persistent config and data for R packages](https://blog.r-hub.io/2020/03/12/user-preferences/) and the [getlandsat](https://docs.ropensci.org/getlandsat/) package
- Carbon Dioxide dataset: Dr. Pieter Tans, NOAA/GML (www.esrl.noaa.gov/gmd/ccgg/trends/) and Dr. Ralph Keeling, Scripps Institution of Oceanography (www.scrippsco2.ucsd.edu/).
- Caching data sets: ROpenSci guide to [Persistent config and data for R packages](https://blog.r-hub.io/2020/03/12/user-preferences/) and the [getlandsat](https://docs.ropensci.org/getlandsat/) package.
14 changes: 10 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,23 @@ You can install the development version of hockeystick from
remotes::install_github("cortinah/hockeystick")
```

## Example
## Examples

This is a basic example which shows you how to solve a common problem:
Retrieve NOAA/ESRL Mauna Loa CO<sub>2</sub> concentration and plot it:

``` r
library(hockeystick)
## basic example code
ml_co2 <- get_carbon()
plot_carbon(ml_co2)
```

<img src="man/figures/README-example-1.png" width="75%" />

## Acknowledgments

- Carbon Dioxide dataset: Dr. Pieter Tans, NOAA/GML
(www.esrl.noaa.gov/gmd/ccgg/trends/) and Dr. Ralph Keeling, Scripps
Institution of Oceanography (www.scrippsco2.ucsd.edu/).
- Caching data sets: ROpenSci guide to [Persistent config and data for
R packages](https://blog.r-hub.io/2020/03/12/user-preferences/) and
the [getlandsat](https://docs.ropensci.org/getlandsat/) package
the [getlandsat](https://docs.ropensci.org/getlandsat/) package.
1 change: 1 addition & 0 deletions hockeystick.Rproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ StripTrailingWhitespace: Yes
BuildType: Package
PackageUseDevtools: Yes
PackageInstallArgs: --no-multiarch --with-keep.source
PackageRoxygenize: rd,collate,namespace
16 changes: 16 additions & 0 deletions inst/WORDLIST
Original file line number Diff line number Diff line change
@@ -1,8 +1,24 @@
Bacastow
Bainbridge
config
cortinah
Ekdahl
getlandsat
ggplot
github
GML
Guenther
https
Lifecycle
Loa
Mauna
NOAA
NOAA's
ORCID
Pieter
pre
ROpenSci
Scripps
Tellus
tibble
Waterman
Binary file added man/figures/README-example-1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
48 changes: 48 additions & 0 deletions man/get_carbon.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion man/hockeystick-package.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

40 changes: 40 additions & 0 deletions man/plot_carbon.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 047f798

Please sign in to comment.