---
title: "Working with spatial and climate data from GSODR and GSODRdata"
author: "Tomislav Hengl and Adam H. Sparks"
output:
    rmarkdown::html_document:
      toc: true
vignette: >
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteIndexEntry{Working with spatial and climate data from GSODR and GSODRdata}
  %\VignetteEncoding{UTF-8}
---



# Introduction

The GSOD data allow for users to use spatial methods with it.
Using various R packages such as _sf_, you can save data as a GeoPackage file which can be read by most GIS software packages or in R using R's GIS capabilities with other contributed packages as well.

Following is an example of how you might download and save GSOD annual data for a given country, Philippines in this example, and convert it into a KML file for viewing in GoogleEarth.
The second portion uses the same GeoPackage file to import the data back into R and combine the GSOD data with CHELSA data from the [GSODRdata package](https://github.com/adamhsparks/GSODRdata) available from GitHub and plot the station temperatures for daily GSOD, average monthly GSOD and CHELSA temperatures (1979-2013).

## Example - Download and Plot Data for a Single Country

This example will demonstrate how to download data for Philippines for year 2010 and generate a spatial, year summary file, PHL-2010.gpkg, in the user's home directory and link it with climate data from the _GSODRdata_ package.

Download data for Philippines for year 2010 and generate a spatial, year summary file, PHL-2010.gpkg, in the user's home directory.


```r
library(GSODR)
library(sf)
PHL <-
  get_GSOD(years = 2010,
           country = "Philippines",
           max_missing = 5)
```

```
## Warning in serialize(data, node$con): 'package:stats' may not be
## available when loading
```

```
## Warning in serialize(data, node$con): 'package:utils' may not be
## available when loading
```

```
## Warning in serialize(data, node$con): 'package:stats' may not be
## available when loading
```

```
## Warning in serialize(data, node$con): 'package:utils' may not be
## available when loading
```

```
## Warning in serialize(data, node$con): 'package:stats' may not be
## available when loading
```

```
## Warning in serialize(data, node$con): 'package:utils' may not be
## available when loading
```

```
## Warning in serialize(data, node$con): 'package:stats' may not be
## available when loading
```

```
## Warning in serialize(data, node$con): 'package:utils' may not be
## available when loading
```

```
## Warning in serialize(data, node$con): 'package:stats' may not be
## available when loading
```

```
## Warning in serialize(data, node$con): 'package:utils' may not be
## available when loading
```

```
## Warning in serialize(data, node$con): 'package:stats' may not be
## available when loading
```

```
## Warning in serialize(data, node$con): 'package:utils' may not be
## available when loading
```

```
## Warning in serialize(data, node$con): 'package:stats' may not be
## available when loading
```

```
## Warning in serialize(data, node$con): 'package:utils' may not be
## available when loading
```

```
## Warning in serialize(data, node$con): 'package:stats' may not be
## available when loading
```

```
## Warning in serialize(data, node$con): 'package:utils' may not be
## available when loading
```

```r
PHL <- st_as_sf(
  x = PHL,
  coords = c("LONGITUDE", "LATITUDE"),
  crs = "+proj=longlat +datum=WGS84"
)

write_sf(obj = PHL, dsn = file.path(tempdir(), "PHL-2010.gpkg"))
```

## Example - Use the GeoPackage File to Create a KML File

Using the GeoPackage that was just created, you can now create a KML file to open with Google Earth and visualise the data spatially and over time.


```r
library(rgdal)
library(spacetime)
library(plotKML)

layers <- ogrListLayers(dsn = file.path(tempdir(), "PHL-2010.gpkg"))
pnts <-
  readOGR(dsn = file.path(tempdir(), "PHL-2010.gpkg"), layers[1])
```

```
## OGR data source with driver: GPKG 
## Source: "/private/var/folders/yv/4xy6zs3x5qsgj96389nkjvtw0000gn/T/RtmpEinr0P/PHL-2010.gpkg", layer: "PHL-2010"
## with 4709 features
## It has 42 fields
```

```r
# Plot results in Google Earth as a spacetime object:
pnts$DATE = as.Date(paste(pnts$YEAR, pnts$MONTH, pnts$DAY, sep = "-"))
row.names(pnts) <- paste("point", 1:nrow(pnts), sep = "")

tmp_ST <- STIDF(
  sp = as(pnts, "SpatialPoints"),
  time = pnts$DATE - 0.5,
  data = pnts@data[, c("TEMP", "STNID")],
  endTime = pnts$DATE + 0.5
)

shape = "http://maps.google.com/mapfiles/kml/pal2/icon18.png"

kml(
  tmp_ST,
  dtime = 24 * 3600,
  colour = TEMP,
  shape = shape,
  labels = TEMP,
  file.name = "Temperatures_PHL_2010-2010.kml",
  folder.name = "TEMP"
)

system("zip -m Temperatures_PHL_2010-2010.kmz Temperatures_PHL_2010-2010.kml")
```

## Example - Compare the GSOD Weather Data From the Philippines With Climate Data Provided by the _GSODRdata_ Package.

The [`GSODRdata`](https://adamhsparks.github.io/GSODRdata/) package provides climate data from four climate data sets that have been formatted for easy use with the _GSODR_ package.
Following is a description how to install the _GSODRdata_ package and use it to visualise the weather data for the Philippines in 2010 against CHELSA data.

CHELSA (Climatologies at High resolution for the Earth’s Land Surface Areas) are climate data at 30 arc seconds for the Earth's land surface areas.

**Description of CHELSA data from CHELSA website**

> CHELSA is a high resolution (30 arc sec) climate data set for the earth land surface areas currently under development in coorporation [_sic_] with the Department of Geography of the University of Hamburg (Prof. Dr. Jürgen Böhner, Dr. Olaf Conrad, Tobias Kawohl), the Swiss Federal Institute for Forest, Snow and Landscape Research WSL (Prof. Dr. Niklaus Zimmermann), the University of Zurich (Dr. Dirk N. Karger, Dr. Michael Kessler), and the University of Göttingen (Prof. Dr. Holger Kreft).
It includes monthly mean temperature and precipitation patterns for the time period 1979-2013.
CHELSA is based on a quasi-mechanistical statistical downscaling of the ERA interim global circulation model (http://www.ecmwf.int/en/research/climate-reanalysis/era-interim) with a GPCC bias correction (https://www.dwd.de/EN/ourservices/gpcc/gpcc.html) and is freely available  in the download section.

See http://chelsa-climate.org for more information on these data.


```r
if (!require(devtools)) {
  install.packages("devtools",
                   repos = c(CRAN = "https://cloud.r-project.org/"))
  library(devtools)
}
devtools::install_github("adamhsparks/GSODRdata")
```

Now that the extra data have been installed, take a look at the CHELSA data that are one of the data sets included in the _GSODRdata_ package.


```r
library(GSODRdata)
library(skimr)

skim(CHELSA)
```


|                         |       |
|:------------------------|:------|
|Name                     |CHELSA |
|Number of rows           |23927  |
|Number of columns        |46     |
|_______________________  |       |
|Column type frequency:   |       |
|character                |1      |
|numeric                  |45     |
|________________________ |       |
|Group variables          |None   |


**Variable type: character**

|skim_variable | n_missing| complete_rate| min| max| empty| n_unique| whitespace|
|:-------------|---------:|-------------:|---:|---:|-----:|--------:|----------:|
|STNID         |         0|             1|  12|  12|     0|    23821|          0|


**Variable type: numeric**

|skim_variable               | n_missing| complete_rate|   mean|     sd|    p0|    p25|   p50|     p75|   p100|hist  |
|:---------------------------|---------:|-------------:|------:|------:|-----:|------:|-----:|-------:|------:|:-----|
|CHELSA_bio10_1979-2013_V1_1 |         0|             1|  22.59|   5.57|  -9.1|  18.20|  22.8|   26.80|   39.3|▁▁▅▇▁ |
|CHELSA_bio11_1979-2013_V1_1 |         0|             1|   4.19|  12.20| -44.1|  -3.60|   3.7|   12.60|   28.5|▁▁▆▇▅ |
|CHELSA_bio1_1979-2013_V1_1  |         0|             1|  13.55|   8.22| -21.1|   7.80|  12.8|   19.70|   31.2|▁▁▇▇▅ |
|CHELSA_bio12_1979-2013_V1_1 |         0|             1| 910.16| 612.07|   0.2| 492.05| 782.8| 1196.20| 9701.5|▇▁▁▁▁ |
|CHELSA_bio13_1979-2013_V1_1 |         0|             1| 135.34| 104.42|   0.1|  74.30| 104.7|  161.00| 2083.5|▇▁▁▁▁ |
|CHELSA_bio14_1979-2013_V1_1 |         0|             1|  34.36|  32.27|   0.0|   9.30|  27.6|   51.70|  384.9|▇▁▁▁▁ |
|CHELSA_bio15_1979-2013_V1_1 |         0|             1|  48.27|  31.17|   6.8|  23.30|  39.9|   66.30|  206.0|▇▃▂▁▁ |
|CHELSA_bio16_1979-2013_V1_1 |         0|             1| 387.24| 295.97|   0.1| 214.10| 302.0|  462.95| 5869.1|▇▁▁▁▁ |
|CHELSA_bio17_1979-2013_V1_1 |         0|             1| 109.86| 101.59|   0.0|  31.50|  88.3|  164.10| 1195.6|▇▁▁▁▁ |
|CHELSA_bio18_1979-2013_V1_1 |         0|             1| 254.12| 202.56|   0.0| 128.40| 223.7|  325.20| 5021.5|▇▁▁▁▁ |
|CHELSA_bio19_1979-2013_V1_1 |         0|             1| 183.24| 198.41|   0.0|  61.65| 131.9|  232.60| 5034.3|▇▁▁▁▁ |
|CHELSA_bio2_1979-2013_V1_1  |         0|             1|  19.31|   5.87|   3.0|  15.20|  20.1|   23.70|   30.6|▁▃▆▇▃ |
|CHELSA_bio3_1979-2013_V1_1  |         0|             1|  52.44|  10.01|  29.3|  45.40|  50.1|   57.00|   93.3|▁▇▃▁▁ |
|CHELSA_bio4_1979-2013_V1_1  |         0|             1| 673.06| 348.80|   7.6| 414.90| 698.3|  892.60| 2319.2|▅▇▃▁▁ |
|CHELSA_bio5_1979-2013_V1_1  |         0|             1|  32.03|   5.58|  -1.5|  29.30|  32.3|   35.30|   49.8|▁▁▃▇▁ |
|CHELSA_bio6_1979-2013_V1_1  |         0|             1|  -6.74|  15.41| -55.5| -17.30|  -6.8|    3.75|   25.5|▁▃▇▇▃ |
|CHELSA_bio7_1979-2013_V1_1  |         0|             1|  38.77|  14.59|   4.0|  28.80|  39.7|   48.20|   87.7|▂▆▇▃▁ |
|CHELSA_bio8_1979-2013_V1_1  |         0|             1|  17.65|   7.66| -29.6|  12.00|  18.2|   24.40|   35.7|▁▁▂▇▅ |
|CHELSA_bio9_1979-2013_V1_1  |         0|             1|   9.90|  13.74| -36.3|  -1.40|  11.4|   21.70|   39.3|▁▃▇▇▅ |
|CHELSA_prec_10_1979-2013    |         0|             1|  77.46|  65.43|   0.0|  34.20|  65.3|   97.00|  647.0|▇▁▁▁▁ |
|CHELSA_prec_11_1979-2013    |         0|             1|  72.50|  63.95|   0.0|  29.30|  59.7|   93.00|  596.4|▇▁▁▁▁ |
|CHELSA_prec_1_1979-2013     |         0|             1|  68.28|  69.25|   0.0|  22.00|  49.7|   87.00|  680.0|▇▁▁▁▁ |
|CHELSA_prec_12_1979-2013    |         0|             1|  70.82|  66.84|   0.0|  23.80|  54.0|   93.50|  681.5|▇▁▁▁▁ |
|CHELSA_prec_1979-2013_land  |         0|             1| 910.00| 612.88|   0.2| 491.80| 781.7| 1195.00| 9773.6|▇▁▁▁▁ |
|CHELSA_prec_2_1979-2013     |         0|             1|  61.29|  60.98|   0.0|  21.30|  43.9|   78.70|  535.8|▇▁▁▁▁ |
|CHELSA_prec_3_1979-2013     |         0|             1|  67.59|  60.06|   0.0|  27.80|  51.3|   90.90|  605.3|▇▁▁▁▁ |
|CHELSA_prec_4_1979-2013     |         0|             1|  66.02|  53.50|   0.0|  30.30|  53.4|   86.60|  524.0|▇▁▁▁▁ |
|CHELSA_prec_5_1979-2013     |         0|             1|  76.52|  61.01|   0.0|  36.80|  63.8|   99.10|  832.5|▇▁▁▁▁ |
|CHELSA_prec_6_1979-2013     |         0|             1|  87.07|  78.40|   0.0|  41.30|  74.3|  107.50| 1201.9|▇▁▁▁▁ |
|CHELSA_prec_7_1979-2013     |         0|             1|  92.22|  90.25|   0.0|  41.00|  76.0|  112.70| 1278.6|▇▁▁▁▁ |
|CHELSA_prec_8_1979-2013     |         0|             1|  89.22|  83.84|   0.0|  38.80|  73.7|  108.70|  964.8|▇▁▁▁▁ |
|CHELSA_prec_9_1979-2013     |         0|             1|  83.46|  72.62|   0.0|  37.60|  67.6|  102.30|  710.5|▇▁▁▁▁ |
|CHELSA_temp_10_1979-2013    |         0|             1|  14.42|   8.14| -23.6|   8.70|  13.5|   20.80|   32.9|▁▁▆▇▅ |
|CHELSA_temp_11_1979-2013    |         0|             1|   9.88|  10.65| -30.8|   2.80|   8.5|   18.60|   33.2|▁▂▇▆▅ |
|CHELSA_temp_1_1979-2013     |         0|             1|   5.09|  13.63| -44.7|  -4.00|   3.6|   16.40|   33.5|▁▂▇▆▅ |
|CHELSA_temp_12_1979-2013    |         0|             1|   6.26|  12.72| -43.0|  -2.00|   4.7|   16.60|   33.0|▁▂▇▇▅ |
|CHELSA_temp_1979-2013_land  |         0|             1|  13.55|   8.22| -21.1|   7.80|  12.8|   19.70|   31.3|▁▁▇▇▅ |
|CHELSA_temp_2_1979-2013     |         0|             1|   6.29|  13.02| -39.1|  -2.80|   4.6|   17.60|   32.4|▁▂▇▆▅ |
|CHELSA_temp_3_1979-2013     |         0|             1|   9.53|  11.01| -28.5|   1.50|   7.8|   18.80|   32.3|▁▂▇▆▅ |
|CHELSA_temp_4_1979-2013     |         0|             1|  13.42|   8.61| -23.0|   7.10|  12.3|   19.60|   34.7|▁▁▇▆▃ |
|CHELSA_temp_5_1979-2013     |         0|             1|  17.01|   6.95| -16.0|  12.00|  16.1|   22.10|   36.5|▁▁▇▇▂ |
|CHELSA_temp_6_1979-2013     |         0|             1|  19.80|   6.37| -10.6|  15.20|  19.6|   24.70|   38.5|▁▁▇▇▁ |
|CHELSA_temp_7_1979-2013     |         0|             1|  19.80|   6.37| -10.6|  15.20|  19.6|   24.70|   38.5|▁▁▇▇▁ |
|CHELSA_temp_8_1979-2013     |         0|             1|  21.09|   6.07| -11.1|  16.80|  21.3|   25.90|   39.1|▁▁▆▇▁ |
|CHELSA_temp_9_1979-2013     |         0|             1|  18.39|   6.56| -17.4|  13.50|  17.9|   23.80|   35.6|▁▁▅▇▃ |

Compare the GSOD weather data from the Philippines with climatic data provided by the _GSODRdata_ package in the CHELSA data set using `dplyr` functions to join the CHELSA and _GSODR_ data for plotting.


```r
library(dplyr)
library(ggplot2)
library(reshape2)

cnames <- paste0("CHELSA_temp_", 1:12, "_1979-2013")
clim_temp <- CHELSA[CHELSA$STNID %in% pnts$STNID,
                    paste(c("STNID", cnames))]
clim_temp_df <- data.frame(
  STNID = rep(clim_temp$STNID, 12),
  MONTHC = as.vector(sapply(1:12, rep,
                            times = nrow(clim_temp))),
  CHELSA_TEMP = as.vector(unlist(clim_temp[, cnames]))
)

pnts$MONTHC <- as.numeric(paste(pnts$MONTH))
temp <-
  left_join(pnts@data, clim_temp_df, by = c("STNID", "MONTHC"))
```

```
## Warning: Column `STNID` joining factors with different levels,
## coercing to character vector
```

```r
temp <- temp %>%
  group_by(MONTH) %>%
  mutate(AVG_DAILY_TEMP = round(mean(TEMP), 1))

df_melt <-
  na.omit(melt(temp[, c("STNID", "DATE", "CHELSA_TEMP", "TEMP", "AVG_DAILY_TEMP")],
               id = c("DATE", "STNID")))

ggplot(df_melt, aes(x = DATE, y = value)) +
  geom_point(aes(color = variable), alpha = 0.2) +
  scale_x_date(date_labels = "%b") +
  ylab("Temperature (C)") +
  xlab("Month") +
  labs(colour = "") +
  scale_color_brewer(palette = "Dark2") +
  facet_wrap( ~ STNID) +
  theme_classic()
```

![plot of chunk comparison](comparison-1.png)

# Notes

## Sources

#### CHELSA Climate Layers
CHELSA (climatic surfaces at 1 km resolution) is based on a quasi-mechanistical
statistical downscaling of the ERA interim global circulation model (Karger et
al. 2016). ESA's CCI-LC cloud probability monthly averages are based
on the MODIS snow products (MOD10A2). <http://chelsa-climate.org/>

## WMO Resolution 40. NOAA Policy

*Users of these data should take into account the following (from the [NCEI website](http://www7.ncdc.noaa.gov/CDO/cdoselect.cmd?datasetabbv=GSOD&countryabbv=&georegionabbv=)):*

> "The following data and products may have conditions placed on their international commercial use.
They can be used within the U.S. or for non-commercial international activities without restriction.
The non-U.S. data cannot be redistributed for commercial purposes.
Re-distribution of these data by others must provide this same notification." [WMO Resolution 40. NOAA Policy](https://public.wmo.int/en/our-mandate/what-we-do/data-exchange-and-technology-transfer)

# References

Karger, D. N., Conrad, O., Bohner, J., Kawohl, T., Kreft, H., Soria-Auza, R. W., *et al*. (2016) Climatologies at high resolution for the Earth land surface areas. *arXiv preprint* **arXiv:1607.00217**. (<http://chelsa-climate.org/>)

Stachelek, J. (2016) Using the Geopackage Format with R. URL: https://jsta.github.io/2016/07/14/geopackage-r.html
