-
Notifications
You must be signed in to change notification settings - Fork 17
/
_main.Rmd
4823 lines (3502 loc) · 190 KB
/
_main.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "R as GIS for Economists"
author: "Taro Mieno"
date: "`r Sys.Date()`"
site: bookdown::bookdown_site
documentclass: book
bibliography: [RGIS.bib]
biblio-style: apalike
link-citations: yes
description: "This is a minimal example of using the bookdown package to write a book. The output format for this example is bookdown::gitbook."
---
# Preface {-}
This book is being developed as part of my effort to put together course materials for my data science course targeted at upper-level undergraduate and graduate students at the University of Nebraska Lincoln. This books aims particularly at **spatial data processing for an econometric project**, where spatial variables become part of an econometric analysis. Over the years, I have seen so many students and researchers who spend so much time just processing spatial data (often involving clicking the ArcGIS (or QGIS) user interface to death), which is a waste of time from the perspective of academic productivity. My hope is that this book will help researchers become more proficient in spatial data processing and enhance the overall productivity of the fields of economics for which spatial data are essential.
**About me**
I am an Assistant Professor at the Department of Agricultural Economics at University of Nebraska Lincoln, where I also teach Econometrics for Master's students. My research interests lie in precision agriculture, water economics, and agricultural policy. My personal website is [here](http://taromieno.netlify.com/).
**Comments and Suggestions?**
Any constructive comments and suggestions about how I can improve the book are all welcome. Please send me an email at [email protected] or create an issue on [the github page](https://github.com/tmieno2/R-as-GIS-for-Economists) of this book.
<hr>
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.
## Why R as GIS for Economists? {-}
R has extensive capabilities as GIS software. In my opinion, $99\%$ of your spatial data processing needs as an economist will be satisfied by R. But, there are several popular options for GIS tasks other than R:
+ Python
+ ArcGIS
+ QGIS
Here I compare them briefly and discuss why R is a good option.
### R vs Python {-}
Both R and Python are actually heavily dependent on open source software GDAL and GEOS for their core GIS operations (GDAL for reading spatial data, and GEOS for geometrical operations like intersecting two spatial layers).^[For example, see the very first sentence of [this page](https://cran.r-project.org/web/packages/sf/index.html)] So, when you run GIS tasks on R or Python you basically tell R or Python what you want to do and they talk to the software, let them do the job, and return the results back to us. This means that R and Python are not very different in its capability at GIS tasks as they are dependent on the common open source software for many GIS tasks. When GDAL and GEOS get better, R and Python get better (with a short lag). Both of them have good spatial visualization tools as well. Moreover, both R and Python can communicate with QGIS and ArcGIS (as long you as have them installed of course) and use their functionalities from within R and Python via the bridging packages: `RQGIS` and `PyQGIS` for QGIS, and `R-ArcGIS` and `ArcPy`.^[We do not learn them in this lecture note because I do not see the benefits of using them.] So, if you are more familiar with Python than R, go ahead and go for the Python option. From now on, my discussions assume that you are going for the R option, as otherwise, you would not be reading the rest of the book anyway.
### R vs ArcGIS or QGIS {-}
ArcGIS is commercial software and it is quite expensive (you are likely to be able to get a significant discount if you are a student at or work for a University). On the other hand, QGIS is open source and free. It has seen significant developments over the decade, and I would say it is just as competitive as ArcGIS. QGIS also uses open source geospatial software GDAL, GEOS, and others (SAGA, GRASS GIS). Both of them have a graphical interface that helps you implement various GIS tasks unlike R which requires programming.
Now, since R can use ArcGIS and QGIS through the bridging packages, a more precise question we should be asking is whether you should program GIS tasks using R (possibly using the bridging packages) or manually implement GIS tasks using the graphical interface of ArcGIS or QGIS. The answer is programming GIS tasks using R. First, manual GIS operations are hard to repeat. It is often the case that in the course of a project you need to redo the same GIS task except that the underlying datasets have changed. If you have programmed the process with R, you just run the same code and that's it. You get the desired results. If you did not program it, you need to go through many clicks on the graphical interface all over again, potentially trying to remember how you actually did it last time.^[You could take a step by step note of what you did though.] Second and more important, manual operations are not scalable. It has become much more common that we need to process many large spatial datasets. Imagine you are doing the same operations on $1,000$ files using a graphical interface, or even $50$ files. Do you know who is good at doing the same tasks over and over again without complaining? A computer. Just let them do what they like to do. You have better things do.
Finally, should you learn ArcGIS or QGIS in addition to (or before) R? I am doubtful. As economists, GIS tasks we need to do are not super convoluted most of the time. Suppose $\Omega_R$ and $\Omega_{AQ}$ represent the set of GIS tasks R and $ArcGIS/QGIS$ can implement, respectively. Further, let $\Omega_E$ represent the set of skills economists need to implement. Then, $\Omega_E \in \Omega_R$ $99\%$ (or maybe $95\%$ to be safe) of the time and $\Omega_E \not\subset \Omega_{AQ}\setminus\Omega_R$ $99\%$ of the time. Personally, I have never had to rely on either ArcGIS or QGIS for my research projects after I learn how to use R as GIS.
One of the things ArcGIS and QGIS can do but R cannot do ($\Omega_{AQ}\setminus\Omega_R$) is creating spatial objects by hand using a graphical user interface, like drawing polygons and lines. Another thing that R lags behind ArcGIS and QGIS is 3D data visualization. But, I must say neither of them is essential for economists at the moment. Finally, sometime it is easier and faster to make a map using ArcGIS and QGIS especially for a complicated map.^[Let me know if you know something that is essential for economists that only ArcGIS or QGIS can do. I will add that to the list her.]
### Summary {-}
+ **You have never used any GIS software?**
Learn R first. If you find out you really really cannot complete the tasks you would like to do on R, then turn to other options.
+ **You have used ArcGIS or QGIS and do not like them because they crash often?**
Why don't you try R?^[I am not saying R does not crash. R does crash. But, often times, the fault is yours, not the software's.] You may realize you actually do not need them.
+ **You have used ArcGIS or QGIS before and are so comfortable with them, but need to program repetitive GIS tasks?**
Learn R and maybe take advantage of `R-ArcGIS` or `RQGIS`, which this book does not cover.
+ **You know for sure that you need to run only a simple GIS task once and never have to do any GIS tasks ever again?**
Stop reading and ask one of your friends to do the job. Pay him/her $\$20$ per hour, which is way below the opportunity cost of setting up either ArcGIS or QGI and learning to do that simple task on them.
## How is this book different from other online books and resources? {-}
We are seeing an explosion of online (and free) resources that teach how to use R for spatial data processing.^[This phenomenon is largely thanks to packages like `bookdown` [@Rbookdown], `blogdown` [@Rblogdown], and `pkgdown` [@Rpkgdown] that has lowered the cost of professional contents creation much much lower than before. Indeed, this book was built taking advantage of the `bookdown` package.] Here is an incomplete list of such resources:
+ [Geocomputation with R](https://geocompr.robinlovelace.net/)
+ [Spatial Data Science](https://keen-swartz-3146c4.netlify.app/)
+ [Spatial Data Science with R](https://www.rspatial.org/index.html)
+ [Introduction to GIS using R](https://www.jessesadler.com/post/gis-with-r-intro/)
+ [Code for An Introduction to Spatial Analysis and Mapping in R](https://bookdown.org/lexcomber/brunsdoncomber2e/)
+ [Introduction to GIS in R](https://annakrystalli.me/intro-r-gis/index.html)
+ [Intro to GIS and Spatial Analysis](https://mgimond.github.io/Spatial/index.html)
+ [Introduction to Spatial Data Programming with R](http://132.72.155.230:3838/r/)
+ [Reproducible GIS analysis with R](http://staff.washington.edu/phurvitz/r_gis/)
+ [R for Earth-System Science](http://geog.uoregon.edu/bartlein/courses/geog490/index.html)
+ [Rspatial](http://rspatial.org/index.html)
+ [NEON Data Skills](https://www.neonscience.org/resources/data-skills)
+ [Simple Features for R](https://r-spatial.github.io/sf/)
<!-- + [Nick Eubank](https://www.nickeubank.com/gis-in-r/) -->
Thanks to all these resources, it has become much easier to self-teach R for GIS work than six or seven years ago when I first started using R for GIS. Even though I have not read through all these resources carefully, I am pretty sure every topic found in this book can also be found _somewhere_ in these resources (except the demonstrations). So, you may wonder why on earth you can benefit from reading this book. It all boils down to search costs. Researchers in different disciplines require different sets of spatial data skills. The available resources are either very general covering so many topics that economists are very unlikely to use. It is particularly hard for those who do not have much experience in GIS to identify whether particular skills are essential or not. So, they could spend so much time learning something that is not really useful. The value of this book lies in its deliberate incomprehensiveness. It only packages materials that satisfy the need of most economists, cutting out many topics that are likely to be of limited use for economists.
For those who are looking for more comprehensive treatments of spatial data handling and processing in one book, I personally like [Geocomputation with R](https://geocompr.robinlovelace.net/) a lot. Increasingly, the developer of R packages created a website dedicated to their R packages, where you can often find vignettes (tutorials), like [Simple Features for R](https://r-spatial.github.io/sf/).
## What is going to be covered in this book? {-}
The book starts with the very basics of spatial data handling (e.g., importing and exporting spatial datasets) and moves on to more practical spatial data operations (e.g., spatial data join) that are useful for research projects. This books is still under development. Right now, only Chapter 1 is available. I will work on the rest of the book over the summer. The "coming soon" chapters are close to be done. I just need to add finishing touches to those chapters. The "wait a bit" chapters need some more work, adding contents, etc.
+ Chapter 1: Demonstrations of R as GIS (available)
* groundwater pumping and groundwater level
* precision agriculture
* land use and weather
* corn planted acreage and railroads
* groundwater pumping and weather
+ Chapter 2: The basics of vector data handling using `sf` package (coming soon)
* spatial data structure in `sf`
* import and export vector data
* (re)projection of spatial datasets
* single-layer geometrical operations (e.g., create buffers, find centroids)
* other miscellaneous basic operations
+ Chapter 3: Spatial interactions of vector datasets (coming soon)
* spatially subsetting one layer based on another layer
* extracting values from one layer to another layer^[`over` function in `sp` language]
+ Chapter 4: The basics of raster data handling using `raster` and `terra` packages (coming soon)
* import and export raster data
* stacking raster data
+ Chapter 5: Spatial interactions of vector and raster datasets (wait a bit)
* extracting values from a raster layer to a vector layer
+ Chapter 6: Efficient spatial data processing (wait a bit)
* parallelization
+ Chapter 7: Downloading publicly available spatial datasets (wait a bit)
* Sentinel 2 (`sen2r`)
* USDA NASS QuickStat (`tidyUSDA`)
* PRISM (`prism`)
* Daymet (`daymetr`)
* USGS (`dataRetrieval`)
+ Chapter 8: Parallel computation (wait a bit)
As you can see above, this book does not spend any time on the very basics of GIS concepts. Before you start reading the book, you should know the followings at least (it's not much):
+ What Geographic Coordinate System (GCS), Coordinate Reference System (CRS), and projection are ([this](https://annakrystalli.me/intro-r-gis/gis.html) is a good resource)
+ Distinctions between vector and raster data ([this](https://gis.stackexchange.com/questions/57142/what-is-the-difference-between-vector-and-raster-data-models) is a simple summary of the difference)
Finally, this book does not cover spatial statistics or spatial econometrics at all. This book is about spatial data _processing_. Spatial analysis is something you do _after_ you have processed spatial data.
## Conventions of the book and some notes {-}
Here are some notes of the conventions of this book and notes for R beginners and those who are not used to reading `rmarkdown`-generated html documents.
### Texts in gray boxes {-}
They are one of the following:
+ objects defined on R during demonstrations
+ R functions
+ R packages
When it is a function, I always put parentheses at the end like this: `st_read()`.^[This is a function that draws values randomly from the uniform distribution.] Sometimes, I combine a package and function in one like this: `sf::st_read()`. This means it is a function called `st_read()` from the `sf` package.
### Colored Boxes {-}
Codes are in blue boxes, and outcomes are in red boxes.
Codes:
```{r codes, eval = F}
runif(5)
```
Outcomes:
```{r outcomes, echo = F}
runif(5)
```
### Parentheses around codes {-}
Sometimes you will see codes enclosed by parenthesis like this:
```{r notes_par}
(
a <- runif(5)
)
```
The parentheses prints what's inside of a newly created object (here `a`) without explicitly evaluating the object. So, basically I am signaling that we will be looking inside of the object that was just created.
This one prints nothing.
```{r notes_par_nodisp}
a <- runif(5)
```
### Footnotes {-}
Footnotes appear at the bottom of the page. You can easily get to a footnote by clicking on the footnote number. You can also go back to the main narrative where the footnote number is by clicking on the curved arrow at the end of the footnote. So, don't worry about having to scroll all the way up to where you were after reading footnotes.
## Session Information {-}
Here is the session information when compiling the book:
```{r session_info}
sessionInfo()
```
<!--chapter:end:index.Rmd-->
# R as GIS: Demonstrations {#demo}
```{r setup, echo = FALSE, results = "hide"}
library(knitr)
knitr::opts_chunk$set(
echo = TRUE,
cache = TRUE,
comment = NA,
message = FALSE,
warning = FALSE,
tidy = FALSE,
cache.lazy = FALSE
)
suppressMessages(library(here))
opts_knit$set(root.dir = here())
```
```{r setwd, eval = FALSE, echo = FALSE}
setwd(here())
```
```{r, echo=FALSE, warning=FALSE, cache = FALSE}
#--- load packages ---#
suppressMessages(library(data.table))
suppressMessages(library(here))
suppressMessages(library(stringr))
suppressMessages(library(rgeos))
suppressMessages(library(sf))
suppressMessages(library(ggplot2))
suppressMessages(library(raster))
suppressMessages(library(stargazer))
suppressMessages(library(tmap))
suppressMessages(library(future.apply))
suppressMessages(library(lubridate))
suppressMessages(library(tidyverse))
#--- source functions ---#
source("Codes/Chap_1_Demonstration.R")
```
## Introduction {-}
The primary objective of this chapter is to showcase the power of R as GIS through demonstrations using mock-up econometric research projects^[Note that this lecture does not deal with spatial econometrics at all. This lecture is about spatial data processing, not spatial econometrics. [This](http://www.econ.uiuc.edu/~lab/workshop/Spatial_in_R.html) is a great resource for spatial econometrics in R.]. Each project consists of a project overview (objective, datasets used, econometric model, and GIS tasks involved) and demonstration. This is really not a place you learn the nuts and bolts of how R does spatial operations. Indeed, we intentionally do not explain all the details of how the R codes work. We reiterate that the main purpose of the demonstrations is to get you a better idea of how R can be used to process spatial data to help your research projects involving spatial datasets. Finally, note that these *mock-up* projects use extremely simple econometric models that completely lacks careful thoughts you would need in real research projects. So, don't waste your time judging the econometric models, and just focus on GIS tasks. If you are not familiar with html documents generated by `rmarkdown`, you might benefit from reading the conventions of the book in the Preface.
### Target Audience {-}
The target audience of this chapter is those who are not very familiar with R as GIS. Knowledge of R certainly helps. But, I tried to write in a way that R beginners can still understand the power of R as GIS^[I welcome any suggestions to improve the reading experience of unexperienced R users.]. Do not get bogged down by all the complex-looking R codes. Just focus on the narratives and figures to get a sense of what R can do.
### Direction for replication {-}
Running the codes in this chapter involves reading datasets from a disk. All the datasets that will be imported are available [here](https://www.dropbox.com/sh/cyx9clgmshwc8eo/AAApv03Qpx84IGKCyF5v2rJ6a?dl=0). In this chapter, the path to files is set relative to my own working directory (which is hidden). To run the codes without having to mess with paths to the files, follow these steps:^[I thought about using the `here` package, but I found it a bit confusing for unexperienced R users.]
+ set a folder (any folder) as the working directory using `setwd()`
+ create a folder called "Data" inside the folder designated as the working directory
+ download the pertinent datasets from [here](https://www.dropbox.com/sh/cyx9clgmshwc8eo/AAApv03Qpx84IGKCyF5v2rJ6a?dl=0) and put them in the "Data" folder
+ run _Chap_1_Demonstration.R_ which is included in the datasets folder you have downloaded
```{r source_functions, eval = F}
source("Data/Chap_1_Demonstration.R")
```
Note that the data folder includes 183-day worth of PRISM precipitation data for Demonstration 3, which are quite large in size (slightly less than 1 GB). If you are not replicating Demonstration 3, you can either choose not to download them or discard them if you have downloaded them already.
## Demonstration 1: The impact of groundwater pumping on depth to water table {#Demo1}
<!-- this is for making stargazer table nicer -->
```{r table_style_demo1, results="asis", echo=FALSE}
cat("
<style>
.book .book-body .page-wrapper .page-inner section.normal table
{
width:auto;
}
.book .book-body .page-wrapper .page-inner section.normal table td,
.book .book-body .page-wrapper .page-inner section.normal table th,
.book .book-body .page-wrapper .page-inner section.normal table tr
{
padding:0;
border:0;
background-color:#fff;
}
</style>
")
```
### Project Overview
---
**Objective:**
* Understand the impact of groundwater pumping on groundwater level.
---
**Datasets**
* Groundwater pumping by irrigation wells in Chase, Dundy, and Perkins Counties in the southwest corner of Nebraska
* Groundwater levels observed at USGS monitoring wells located in the three counties and retrieved from the National Water Information System (NWIS) maintained by USGS using the `dataRetrieval` package.
---
**Econometric Model**
In order to achieve the project objective, we will estimate the following model:
$$
y_{i,t} - y_{i,t-1} = \alpha + \beta gw_{i,t-1} + v
$$
where $y_{i,t}$ is the depth to groundwater table^[the distance from the surface to the top of the aquifer] in March^[For our geographic focus of southwest Nebraska, corn is the dominant crop type. Irrigation for corn happens typically between April through September. For example, this means that changes in groundwater level ($y_{i,2012} - y_{i,2011}$) captures the impact of groundwater pumping that occurred April through September in 2011.] in year $t$ at USGS monitoring well $i$, and $gw_{i,t-1}$ is the total amount of groundwater pumping that happened within the 2-mile radius of the monitoring well $i$.
---
**GIS tasks**
* read an ESRI shape file as an `sf` (spatial) object
- use `sf::st_read()`
* download depth to water table data using the `dataRetrieval` package developed by USGS
- use `dataRetrieval::readNWISdata()` and `dataRetrieval::readNWISsite()`
* create a buffer around USGS monitoring wells
- use `sf::st_buffer()`
* convert a regular `data.frame` (non-spatial) with geographic coordinates into an `sf` (spatial) objects
- use `sf::st_as_sf()` and `sf::st_set_crs()`
* reproject an `sf` object to another CRS
- use `sf::st_transform()`
* identify irrigation wells located inside the buffers and calculate total pumping
- use `sf::st_join()`
---
**packages**
+ Load (install first if you have not) the following packages if you intend to replicate the demonstration.
```{r demo1_packages, eval = FALSE}
library(sf)
library(dplyr)
library(lubridate)
library(stargazer)
```
There are other packages that will be loaded during the demonstration.
### Project Demonstration
The geographic focus of the project is the southwest corner of Nebraska consisting of Chase, Dundy, and Perkins County (see Figure \@ref(fig:NE-county) for their locations within Nebraska). Let's read a shape file of the three counties represented as polygons. We will use it later to spatially filter groundwater level data downloaded from NWIS.
```{r NE_county_data, echo = FALSE, results = "hide"}
#--- Nebraska counties ---#
NE_county <- st_read(
dsn = "./Data",
layer = "cb_2018_us_county_20m"
) %>%
filter(STATEFP == "31") %>%
mutate(NAME = as.character(NAME)) %>%
st_transform(32614)
three_counties <- st_read(dsn = "./Data", layer = "urnrd") %>%
st_transform(32614)
```
```{r Demo1_read_urnrd_borders}
three_counties <- st_read(dsn = "./Data", layer = "urnrd") %>%
#--- project to WGS84/UTM 14N ---#
st_transform(32614)
```
```{r NE-county, fig.cap = "The location of Chase, Dundy, and Perkins County in Nebraska", echo =F}
#--- map the three counties ---#
tm_shape(NE_county) +
tm_polygons() +
tm_shape(three_counties) +
tm_polygons(col = "blue", alpha = 0.3) +
tm_layout(frame = FALSE)
```
---
We have already collected groundwater pumping data, so let's import it.
```{r Demo1_urnrd_gw_read}
#--- groundwater pumping data ---#
(
urnrd_gw <- readRDS("./Data/urnrd_gw_pumping.rds")
)
```
`well_id` is the unique irrigation well identifier, and `vol_af` is the amount of groundwater pumped in acre-feet. This dataset is just a regular `data.frame` with coordinates. We need to convert this dataset into a object of class `sf` so that we can later identify irrigation wells located within a 2-mile radius of USGS monitoring wells (see Figure \@ref(fig:sp-dist-wells) for the spatial distribution of the irrigation wells).
```{r convert_to_sf}
urnrd_gw_sf <- urnrd_gw %>%
#--- convert to sf ---#
st_as_sf(coords = c("lon", "lat")) %>%
#--- set CRS WGS UTM 14 (you need to know the CRS of the coordinates to do this) ---#
st_set_crs(32614)
#--- now sf ---#
urnrd_gw_sf
```
```{r sp-dist-wells, fig.cap = "Spatial distribution of irrigation wells", echo = FALSE, results = "hide"}
urnrd_gw_sf <- urnrd_gw %>%
#--- convert to sf ---#
st_as_sf(coords = c("lon", "lat")) %>%
#--- set CRS WGS UTM 14 (you need to know the CRS of the coordinates to do this) ---#
st_set_crs(32614)
tm_shape(three_counties) +
tm_polygons() +
tm_shape(unique(urnrd_gw_sf, by = "well_id")) +
tm_symbols(size = 0.1, col = "blue") +
tm_layout(frame = FALSE)
```
---
Here are the rest of the steps we will take to obtain a regression-ready dataset for our analysis.
1. download groundwater level data observed at USGS monitoring wells from National Water Information System (NWIS) using the `dataRetrieval` package
2. identify the irrigation wells located within the 2-mile radius of the USGS wells and calculate the total groundwater pumping that occurred around each of the USGS wells by year
3. merge the groundwater pumping data to the groundwater level data
---
Let's download groundwater level data from NWIS first. The following code downloads groundwater level data for Nebraska from Jan 1, 1990, through Jan 1, 2016.
```{r gwl_data_download, eval = F}
#--- load the dataRetrieval package ---#
library(dataRetrieval)
#--- download groundwater level data ---#
NE_gwl <- readNWISdata(
stateCd="Nebraska",
startDate = "1990-01-01",
endDate = "2016-01-01",
service = "gwlevels"
) %>%
dplyr::select(site_no, lev_dt, lev_va) %>%
rename(date = lev_dt, dwt = lev_va)
#--- take a look ---#
head(NE_gwl, 10)
```
```{r read_NW_gwl, echo = F}
library(dataRetrieval)
NE_gwl <- readRDS("./Data/NE_gwl.rds")
#--- take a look ---#
head(NE_gwl, 10)
```
`site_no` is the unique monitoring well identifier, `date` is the date of groundwater level monitoring, and `dwt` is depth to water table.
We calculate the average groundwater level in March by USGS monitoring well (right before the irrigation season starts):^[`month()` and `year()` are from the `lubridate` package. They extract month and year from a `Date` object.]
```{r avg_march_deptn}
#--- Average depth to water table in March ---#
NE_gwl_march <- NE_gwl %>%
mutate(
date = as.Date(date),
month = month(date),
year = year(date),
) %>%
#--- select observation in March ---#
filter(year >= 2007, month == 3) %>%
#--- gwl average in March ---#
group_by(site_no, year) %>%
summarize(dwt = mean(dwt))
#--- take a look ---#
head(NE_gwl_march, 10)
```
Since `NE_gwl` is missing geographic coordinates for the monitoring wells, we will download them using the `readNWISsite()` function and select only the monitoring wells that are inside the three counties.
```{r NE_sites}
#--- get the list of site ids ---#
NE_site_ls <- NE_gwl$site_no %>% unique()
#--- get the locations of the site ids ---#
sites_info <- readNWISsite(siteNumbers = NE_site_ls) %>%
dplyr::select(site_no, dec_lat_va, dec_long_va) %>%
#--- turn the data into an sf object ---#
st_as_sf(coords = c("dec_long_va", "dec_lat_va")) %>%
#--- NAD 83 ---#
st_set_crs(4269) %>%
#--- project to WGS UTM 14 ---#
st_transform(32614) %>%
#--- keep only those located inside the three counties ---#
.[three_counties, ]
```
---
We now identify irrigation wells that are located within the 2-mile radius of the monitoring wells^[This can alternatively be done using the `st_is_within_distance()` function.]. We first create polygons of 2-mile radius circles around the monitoring wells (see Figure \@ref(fig:buffer-map)).
```{r create_buffer}
buffers <- st_buffer(sites_info, dist = 2*1609.34) # in meter
```
```{r buffer-map, fig.cap = "2-mile buffers around USGS monitoring wells", echo = FALSE}
tm_shape(three_counties) +
tm_polygons() +
tm_shape(buffers) +
tm_polygons(col = "red", alpha = 0,2) +
tm_shape(sites_info) +
tm_symbols(size = 0.1) +
tm_layout(frame = FALSE)
```
We now identify which irrigation wells are inside each of the buffers and get the associated groundwater pumping values. The `st_join()` function from the `sf` package will do the trick.
```{r Demo_join_buffer_gw, cache = FALSE}
#--- find irrigation wells inside the buffer and calculate total pumping ---#
pumping_neaby <- st_join(buffers, urnrd_gw_sf)
```
Let's take a look at a USGS monitoring well (`site_no` = $400012101323401$).
```{r take_a_look}
filter(pumping_neaby, site_no == 400012101323401, year == 2010)
```
As you can see, this well has seven irrigation wells within its 2-mile radius in 2010.
Now, we will get total nearby pumping by monitoring well and year.
```{r Demo1_summary_by_buffer}
(
total_pumping_nearby <- pumping_neaby %>%
#--- calculate total pumping by monitoring well ---#
group_by(site_no, year) %>%
summarize(nearby_pumping = sum(vol_af, na.rm = TRUE)) %>%
#--- NA means 0 pumping ---#
mutate(
nearby_pumping = ifelse(is.na(nearby_pumping), 0, nearby_pumping)
)
)
```
---
We now merge nearby pumping data to the groundwater level data, and transform the data to obtain the dataset ready for regression analysis.
```{r Demo_nearby_merge}
#--- regression-ready data ---#
reg_data <- NE_gwl_march %>%
#--- pick monitoring wells that are inside the three counties ---#
filter(site_no %in% unique(sites_info$site_no)) %>%
#--- merge with the nearby pumping data ---#
left_join(., total_pumping_nearby, by = c("site_no", "year")) %>%
#--- lead depth to water table ---#
arrange(site_no, year) %>%
group_by(site_no) %>%
mutate(
#--- lead depth ---#
dwt_lead1 = dplyr::lead(dwt, n = 1, default = NA, order_by = year),
#--- first order difference in dwt ---#
dwt_dif = dwt_lead1 - dwt
)
#--- take a look ---#
dplyr::select(reg_data, site_no, year, dwt_dif, nearby_pumping)
```
---
Finally, we estimate the model using the `lfe` package.
```{r Demo_reg_dwt}
#--- load the lfe package for regression with fixed effects ---#
library(lfe)
#--- OLS with site_no and year FEs (error clustered by site_no) ---#
reg_dwt <- felm(dwt_dif ~ nearby_pumping | site_no + year | 0 | site_no, data = reg_data)
```
Here is the regression result.
```{r reg_dwt_disp, results = "asis"}
stargazer(reg_dwt, type = "html")
```
## Demonstration 2: Precision Agriculture
```{r table_style_demo2, results="asis", echo=FALSE}
cat("
<style>
.book .book-body .page-wrapper .page-inner section.normal table
{
width:auto;
}
.book .book-body .page-wrapper .page-inner section.normal table td,
.book .book-body .page-wrapper .page-inner section.normal table th,
.book .book-body .page-wrapper .page-inner section.normal table tr
{
padding:0;
border:0;
background-color:#fff;
}
</style>
")
```
### Project Overview
---
**Objectives:**
+ Understand the impact of nitrogen on corn yield
+ Understand how electric conductivity (EC) affects the marginal impact of nitrogen on corn
---
**Datasets:**
+ The experimental design of an on-farm randomized nitrogen trail on an 80-acre field
+ Data generated by the experiment
* As-applied nitrogen rate
* Yield measures
+ Electric conductivity
---
**Econometric Model:**
Here is the econometric model, we would like to estimate:
$$
yield_i = \beta_0 + \beta_1 N_i + \beta_2 N_i^2 + \beta_3 N_i \cdot EC_i + \beta_4 N_i^2 \cdot EC_i + v_i
$$
where $yield_i$, $N_i$, $EC_i$, and $v_i$ are corn yield, nitrogen rate, EC, and error term at subplot $i$. Subplots which are obtained by dividing experimental plots into six of equal-area compartments.
---
**GIS tasks**
* read spatial data in various formats: R data set (rds), shape file, and GeoPackage file
- use `sf::st_read()`
* create maps using the `ggplot2` package
- use `ggplot2::geom_sf()`
* create subplots within experimental plots
- use-defined function that makes use of `st_geometry()`
* identify corn yield, as-applied nitrogen, and electric conductivity (EC) data points within each of the experimental plots and find their averages
- use `sf::st_join()` and `sf::aggregate()`
---
**Preparation for replication**
+ Source (run) *Chap_1_Demonstration.R* to define `theme_map` and `gen_subplots()`
```{r source_demo2, eval = F}
source("Codes/Chap_1_Demonstration.R")
```
+ Load (install first if you have not) the following packages (There are other packages that will be loaded during the demonstration).
```{r demo2_packages, eval = FALSE}
library(sf)
library(dplyr)
library(ggplot2)
library(stargazer)
```
### Project Demonstration
We have already run a whole-field randomized nitrogen experiment on a 80-acre field. Let's import the trial design data
```{r Demo2_exp_design}
#--- read the trial design data ---#
trial_design_16 <- readRDS("./Data/trial_design.rds")
```
Figure \@ref(fig:trial-fig) is the map of the trial design generated using `ggplot2` package.^[`theme_for_map` is a user defined object that defines the theme of figures generated using `ggplot2` for this section. You can find it in **Chap_1_Demonstration.R**.].
```{r trial-fig, fig.cap = "The Experimental Design of the Randomize Nitrogen Trial"}
#--- map of trial design ---#
ggplot(data = trial_design_16) +
geom_sf(aes(fill = factor(NRATE))) +
scale_fill_brewer(name = "N", palette = "OrRd", direction = 1) +
theme_for_map
```
---
We have collected yield, as-applied NH3, and EC data. Let's read in these datasets:^[Here we are demonstrating that R can read spatial data in different formats. R can read spatial data of many other formats. Here, we are reading a shapefile (.shp) and GeoPackage file (.gpkg).]
```{r Demo2_data_experiment, results = "hide"}
#--- read yield data (sf data saved as rds) ---#
yield <- readRDS("./Data/yield.rds")
#--- read NH3 data (GeoPackage data) ---#
NH3_data <- st_read("Data/NH3.gpkg")
#--- read ec data (shape file) ---#
ec <- st_read(dsn="Data", "ec")
```
Figure \@ref(fig:Demo2-show-the-map) shows the spatial distribution of the three variables. A map of each variable was made first, and then they are combined into one figure using the `patchwork` package^[Here is its [github page](https://github.com/thomasp85/patchwork). See the bottom of the page to find vignettes.].
```{r Demo2-show-the-map, fig.cap = "Spatial distribution of yield, NH3, and EC", fig.height = 9}
#--- yield map ---#
g_yield <- ggplot() +
geom_sf(data = trial_design_16) +
geom_sf(data = yield, aes(color = yield), size = 0.5) +
scale_color_distiller(name = "Yield", palette = "OrRd", direction = 1) +
theme_for_map
#--- NH3 map ---#
g_NH3 <- ggplot() +
geom_sf(data = trial_design_16) +
geom_sf(data = NH3_data, aes(color = aa_NH3), size = 0.5) +
scale_color_distiller(name = "NH3", palette = "OrRd", direction = 1) +
theme_for_map
#--- NH3 map ---#
g_ec <- ggplot() +
geom_sf(data = trial_design_16) +
geom_sf(data = ec, aes(color = ec), size = 0.5) +
scale_color_distiller(name = "EC", palette = "OrRd", direction = 1) +
theme_for_map
#--- stack the figures vertically and display ---#
library(patchwork)
g_yield/g_NH3/g_ec
```
---
Instead of using plot as the observation unit, we would like to create subplots inside each of the plots and make them the unit of analysis because it would avoid masking the within-plot spatial heterogeneity of EC. Here, we divide each plot into six subplots^[`gen_subplots` is a user-defined function. See **Chap_1_Demonstration.R**.]:
```{r Demo2_get_subplots}
#--- generate subplots ---#
subplots <- lapply(
1:nrow(trial_design_16),
function(x) gen_subplots(trial_design_16[x, ], 6)
) %>%
do.call('rbind', .)
```
Figure \@ref(fig:map-subgrid) is a map of the subplots generated.
```{r map-subgrid, fig.cap = "Map of the subplots"}
#--- here is what subplots look like ---#
ggplot(subplots) +
geom_sf() +
theme_for_map
```
---
We now identify the mean value of corn yield, nitrogen rate, and EC for each of the subplots using `sf::aggregate()` and `sf::st_join()`.
```{r Demo2_merge_join}
(
reg_data <- subplots %>%
#--- yield ---#
st_join(., aggregate(yield, ., mean), join = st_equals) %>%
#--- nitrogen ---#
st_join(., aggregate(NH3_data, ., mean), join = st_equals) %>%
#--- EC ---#
st_join(., aggregate(ec, ., mean), join = st_equals)
)
```
Here are the visualization of the subplot-level data (Figure \@ref(fig:Demo2-subplot-fig)):
```{r Demo2-subplot-fig, fig.cap = "Spatial distribution of subplot-level yield, NH3, and EC", fig.height = 7}
(ggplot() +
geom_sf(data = reg_data, aes(fill = yield), color = NA) +
scale_fill_distiller(name = "Yield", palette = "OrRd", direction = 1) +
theme_for_map)/
(ggplot() +
geom_sf(data = reg_data, aes(fill = aa_NH3), color = NA) +
scale_fill_distiller(name = "NH3", palette = "OrRd", direction = 1) +
theme_for_map)/
(ggplot() +
geom_sf(data = reg_data, aes(fill = ec), color = NA) +
scale_fill_distiller(name = "EC", palette = "OrRd", direction = 1) +
theme_for_map)
```
---
Let's estimate the model and see the results:
```{r Demo2_results, results = "asis"}
lm(yield ~ aa_NH3 + I(aa_NH3^2) + I(aa_NH3*ec) + I(aa_NH3^2*ec), data = reg_data) %>%
stargazer(type = "html")
```
## Demonstration 3: Land Use and Weather
```{r table_style_demo3, results="asis", echo=FALSE}
cat("
<style>
.book .book-body .page-wrapper .page-inner section.normal table
{
width:auto;
}
.book .book-body .page-wrapper .page-inner section.normal table td,
.book .book-body .page-wrapper .page-inner section.normal table th,
.book .book-body .page-wrapper .page-inner section.normal table tr
{
padding:0;
border:0;
background-color:#fff;
}
</style>
")
```
### Project Overview
---
**Objective**
Understand the impact of past precipitation on crop choice in Iowa (IA).
---
**Datasets**
+ IA county boundary
+ Regular grids over IA, created using `sf::st_make_grid()`
+ PRISM daily precipitation data downloaded using `prism` package
+ Land use data from the Cropland Data Layer (CDL) for IA in 2015, downloaded using `cdlTools` package
---
**Econometric Model**
The econometric model we would like to estimate is:
$$
CS_i = \alpha + \beta_1 PrN_{i} + \beta_2 PrC_{i} + v_i
$$
where $CS_i$ is the area share of corn divided by that of soy in 2015 for grid $i$ (we will generate regularly-sized grids in the Demo section), $PrN_i$ is the total precipitation observed in April through May and September in 2014, $PrC_i$ is the total precipitation observed in June through August in 2014, and $v_i$ is the error term. To run the econometric model, we need to find crop share and weather variables observed at the grids. We first tackle the crop share variable, and then the precipitation variable.
---
**GIS tasks**
+ download Cropland Data Layer (CDL) data by USDA NASS
* use `cdlTools::getCDL()`
+ download PRISM weather data
* use `prism::get_prism_dailys()`
+ crop PRISM data to the geographic extent of IA
* use `raster::crop()`
+ create regular grids within IA, which become the observation units of the econometric analysis
* use `sf::st_make_grid()`
+ remove grids that share small area with IA
* use `sf::st_intersection()` and `sf::st_area`
+ assign crop share and weather data to each of the generated IA grids (parallelized)
* use `exactextractr::exact_extract()` and `future.apply::future_lapply()`
+ create maps
* use `tmap` package
---
**Preparation for replication**
+ Load (install first if you have not) the following packages (There are other packages that will be loaded during the demonstration).
```{r demo3_packages, eval = FALSE}
library(sf)
library(data.table)
library(dplyr)
library(raster)
library(lubridate)
library(tmap)
library(future.apply)
library(stargazer)
```
### Project Demonstration
The geographic focus of this project is IA. Let's get IAs state border (see Figure \@ref(fig:IA-map) for its map).
```{r Demo4_IA_boundary}
library("maps")
#--- IA state boundary ---#
IA_boundary <- st_as_sf(map("state", "iowa", plot = FALSE, fill = TRUE))
```
```{r IA-map, echo = FALSE, fig.cap = "IA state boundary", fig.margin = TRUE}
#--- map IA state border ---#
tm_shape(IA_boundary) +
tm_polygons() +
tm_layout(frame = FALSE)
```
The unit of analysis is artificial grids that we create over IA. The grids are regularly-sized rectangles except around the edge of the IA state border^[We by no means are saying that this is the right geographical unit of analysis. This is just about demonstrating how R can be used for analysis done at the higher spatial resolution than county.]. So, let's create grids and remove those that do not overlap much with IA.
```{r Demo4_IA_grids}
#--- create regular grids (40 cells by 40 columns) over IA ---#
IA_grids <- IA_boundary %>%
#--- create grids ---#
st_make_grid(, n = c(40, 40)) %>%
#--- convert to sf ---#
st_as_sf() %>%
#--- find the intersections of IA grids and IA polygon ---#
st_intersection(., IA_boundary) %>%
#--- calculate the area of each grid ---#
mutate(
area = as.numeric(st_area(.)),
area_ratio = area/max(area)
) %>%
#--- keep only if the intersected area is large enough ---#
filter(area_ratio > 0.8) %>%
#--- assign grid id for future merge ---#
mutate(grid_id = 1:nrow(.))
```
Here is what the generated grids look like (Figure \@ref(fig:Demo4-IA-grids-map)):
```{r Demo4-IA-grids-map, fig.cap = "Map of regular grids generated over IA"}
#--- plot the grids over the IA state border ---#
tm_shape(IA_boundary) +
tm_polygons(col = "green") +
tm_shape(IA_grids) +
tm_polygons(alpha = 0) +
tm_layout(frame = FALSE)
```
---
Let's work on crop share data. You can download CDL data using the `getCDL()` function from the `cdlTools` package.
```{r Demo4_cdl_download}
#--- load the cdlTools package ---#
library(cdlTools)
#--- download the CDL data for IA in 2015 ---#
(
IA_cdl_2015 <- getCDL("Iowa", 2015)$IA2015
)
```
The cells (30 meter by 30 meter) of the imported raster layer take a value ranging from 0 to 255. Corn and soybean are represented by 1 and 5, respectively (visualization of the CDL data is on the right).
Figure \@ref(fig:overlap-cdl-grid) shows the map of one of the IA grids and the CDL cells it overlaps with.
```{r overlap-cdl-grid, fig.cap = "Spatial overlap of a IA grid and CDL layer", echo = FALSE, dependson = "Demo4_cdl_download"}
temp_grid <- IA_grids[100, ]
extent_grid <- temp_grid %>%
st_transform(., projection(IA_cdl_2015)) %>%
extent()
raster_ovelap <- raster::crop(IA_cdl_2015, extent_grid)
tm_shape(raster_ovelap) +
tm_raster() +
tm_shape(temp_grid) +
tm_borders(lwd = 3, col = "blue")
```
We would like to extract all the cell values within the blue border.
We use `exactextractr::exact_extract()` to identify which cells of the CDL raster layer fall within each of the IA grids and extract land use type values. We then find the share of corn and soybean for each of the grids.
```{r Demo4_extract, results = "hide"}
#--- reproject grids to the CRS of the CDL data ---#
IA_grids_rp_cdl <- st_transform(IA_grids, projection(IA_cdl_2015))
#--- load the exactextractr package for fast rater value extractions for polygons ---#
library(exactextractr)
#--- extract crop type values and find frequencies ---#
cdl_extracted <- exact_extract(IA_cdl_2015, IA_grids_rp_cdl) %>%
lapply(., function (x) data.table(x)[,.N, by = value]) %>%
#--- combine the list of data.tables into one data.table ---#
rbindlist(idcol = TRUE) %>%
#--- find the share of each land use type ---#
.[, share := N/sum(N), by = .id] %>%
.[, N := NULL] %>%
#--- keep only the share of corn and soy ---#
.[value %in% c(1, 5), ]
```
We then find the corn to soy ratio for each of the IA grids.
```{r Demo4_share_calc}
#--- find corn/soy ratio ---#
corn_soy <- cdl_extracted %>%
#--- long to wide ---#
dcast(.id ~ value, value.var = "share") %>%
#--- change variable names ---#
setnames(c(".id", "1", "5"), c("grid_id", "corn_share", "soy_share")) %>%
#--- corn share divided by soy share ---#