-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathUsefulCode_sf.Rmd
1500 lines (1199 loc) · 39.9 KB
/
UsefulCode_sf.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: Useful R code - sf and geodata
author: |
| Matthew Malishev
| @darwinanddavis
fontsize: 10
geometry: margin=1in
documentclass: article
linkcolor: pink
urlcolor: blue
citecolor: red
always_allow_html: yes
output:
html_document:
highlight: tango
code_folding: show
toc: yes
toc_depth: 4
number_sections: no
toc_float: yes
md_document:
variant: markdown_github
pdf_document:
includes:
in_header: # add .tex file with header content
highlight: tango
template: null
toc: yes
toc_depth: 4
number_sections: false
fig_width: 4
fig_height: 5
fig_caption: true
df_print: tibble
citation_package: biblatex # natbib
latex_engine: xelatex #pdflatex # lualatex
keep_tex: true # keep .tex file in dir
word_document:
highlight: tango
keep_md: yes
pandoc_args: --smart
#reference: mystyles.docx
toc: yes
toc_depth: 4
inludes:
before_body: before_body.tex
subtitle:
tags:
- nothing
- nothingness
params:
dir: "/Users/malishev/Documents/Melbourne Uni/Programs/R code/UsefulCode"
date: !r Sys.Date()
version: !r getRversion()
email: "matthew.malishev [at] gmail.com"
doi: https://github.com/darwinanddavis/UsefulCode
classoption: portrait
# ^['https://github.com/darwinanddavis/UsefulCode'] # footnote
vignette: >
%\VignetteIndexEntry{Useful R code}
%\VignetteEncoding{UTF-8}
%\VignetteEngine{knitr::rmarkdown}
---
<script type="text/x-mathjax-config">
MathJax.Hub.Config({ TeX: { equationNumbers: {autoNumber: "all"} } });
</script>
```{r echo = FALSE}
library(rmarkdown)
# setwd("")
# f <- list.files()[1]
# render(f, output_format='pdf_document')
# render(f, output_format='pdf_document')
```
```{r, set-options, echo = FALSE, cache = FALSE}
options(width=100)
knitr::opts_chunk$set(
eval = F, # run all code
results='hide',
# echo = FALSE, # show code chunks in output
comment = "",
tidy.opts=list(width.cutoff=100), # set width of code chunks in output
tidy=TRUE, # make output as tidy
message = FALSE, # mask all messages
warning = FALSE, # mask all warnings
collapse = T,
size="small" # set code chunk size
)
# https://github.com/ucb-stat133/stat133-fall-2016/blob/master/hws/hw02-tables-ggplot.Rmd
knitr::opts_knit$set(root.dir=paste0(params$dir,"/")) # set working dir
setwd(paste0(params$dir,"/")) # for running just in R not knitr
pacman::p_load(dplyr,readr,rvest,xml2,magrittr,sp,sf,rgdal,ggmap,ggplot2,stringr,ggthemes,ggnetwork,colorspace,ggtext,ggsn,ggspatial,showtext,here)
```
\
Date: `r params$date`
`R` version: `r params$version`
*Corresponding author: `r params$email`
This document can be found at `r params$doi`
\newpage
## Overview
Accessing sf, sp, geos,a nd geojson objects, such as attributes, accessing lower levels of their structure, latlon and MULTIPOLYGONS layers, etc.
<!-- ideas -->
<!-- https://r-spatial.github.io/sf/articles/sf1.html -->
<!-- https://nceas.github.io/oss-lessons/spatial-data-gis-law/3-mon-intro-gis-in-r.html -->
### json
Read and convert json to df
```{r, json1, eval = F}
# opt 1
require(jsonlite)
data <- fromJSON("data.json",simplifyDataFrame=T,flatten=T) %>%
as.data.frame(data)
# opt 2
file <- "my_geo_data.json" %>%
readr::read_lines
# opt 3
file <- "my_geo_data.json" %>%
read_sf
```
Convert sf to geojson
```{r, json2}
require(geojsonio)
sf %>% geojsonio::geojson_list()
```
Save R obj as geojson
```{r, json3}
# save R obj as geojson
sfjson %>% geojson_write(file = here::here("data”,”new.json"))
# opt 2
sf %>% st_write("sf.geojson")
# opt 3 convert sf to json string and save to dir
sf %>% geojsonio::geojson_list() %>%
rjson::toJSON(method = "C") %>%
readr::write_lines("sf.json")
```
Loop through sf and convert and save as geojson
```{r, json4}
require(geojsonio)
for(i in sf$name){
sf %>% filter(name %in% i) %>% geojson_list() %>%
geojson_write(here::here("data",paste0("newfile",i,".json")))
}
```
Read in json and convert to df
```{r, json5}
require(jsonlite)
read_json("test.json", simplifyVector = T)
```
Write json/geojson to dir
```{r, json6, eval = F}
# write json methods
# working but only points
pacman::p_load(jsonlite,geojsonio)
sf %>% st_write("data.shp") # write shp
sf %>% st_write("data.json") # write json
sf %>% st_write("data.geojson",driver = "geojson") # write geojson
sf %>% st_write("data.json", driver = "geojson", delete_dsn = T) # overwrite file
sf %>% geojsonio::geojson_write(file = "data.json")
sf %>% rjson::toJSON(indent = "2")
sf %>% geojsonio::geojson_list() %>% rjson::toJSON(method = "C") %>% readr::write_lines("sf.json")
sf %>% geojsonio::file_to_geojson(output = "data.geojson")
# convert sf to json
sf %>% jsonlite::toJSON() %>% jsonlite::prettify()
# convert list to geojson
ls %>% rjson::toJSON()
ls %>% jsonify::to_json(unbox = T) %>% jsonify::pretty_json()
```
Check available drivers for writing shp, json, geojson, kml
```{r}
require(rgdal)
ogrDrivers() %>% View
```
### sf simple features
Get bbox coords
```{r, sf1, collapse=T}
require(sf)
methods(class="sf")
obj$geometry %>% attr(which = "bbox")
```
Get first element or range of sf
```{r, sf2}
obj$geometry
obj$geometry[1] %>% unlist %>% .[1] # first element
obj %>% st_coordinates() %>% .[1:3] # coord range
```
Get polygons (and range) in geometry layer
```{r, sf3}
obj %>% st_geometry() %>% .[1:10] # polygon range
```
Remove or keep/select specific sf types from sf obj
```{r, sf4}
obj %>% st_collection_extract("POINT") # get just points
obj %>% st_geometry %>% st_collection_extract("POINT") # get geometry of just points
```
Get boundary/outlines
```{r, sf5}
# good for plotting US state border lines over other sf files
obj %>% st_geometry() %>% st_boundary %>% ggplot() + geom_sf()
# boundary of bbox
mp %>% st_bbox() %>% st_as_sfc() %>%
ggplot() + geom_sf()
```
Break up multipolygon into separate polygons/pull specific polygon e.g. main France polygon and rm islands
```{r, sf6, eval = F}
french_guiana <- ne_countries("large",type = "countries",returnclass = "sf") %>%
filter(name %in% c("France")) %>% # add french guiana
st_cast("POLYGON") %>% slice(1) # get just french guiana
```
Get areas of individual polygons within multipolygon
```{r, sf7}
dd %>% filter(name == "Netherlands") %>%
st_cast("POLYGON") %>% st_geometry %>% st_area()
```
Filter sf geometry only
```{r, sf9}
dat %>%
filter(st_geometry_type(.) == "LINESTRING")
```
Convert matrix directly to sf
```{r, sf10}
require(sfheaders)
m %>% sf_point()
m %>% sf_multipolygon()
m %>% sf_multilinestring()
m %>% sf_linestring()
# convert list of matrices/arrays into sf
require(purrr)
require(magrittr)
require(rlist)
ls %>%
map(matrix, ncol = 2) %>%
map(magrittr::set_colnames, c("lon","lat")) %>% # rename cols
compact() %>% # drop empty lists
map(sfheaders::sf_multipolygon, multipolygon_id = NULL) %>% # convert to sf
rlist::list.rbind() # bind sfs
```
### ZM features
Return Z range for sf obj
```{r,zm1}
sf %>% st_z_range()
```
Drop zm components
```{r}
sf %>% st_zm()
```
### .shp files
Read in .shp file
```{r, s1, collapse=T}
require(rgdal)# \ rgdal
shp <- readOGR(".shp", layer="X") # layer = name of geometry element
```
Get and transform projection
```{r, s2}
require(rgdal)# \ rgdal
proj4string(shp) # get projection
spTransform(shp, CRS("+proj=longlat +datum=WGS84")) # transform projection
```
### Base maps
Base map from OSM
```{r, m1}
# osm
gg <- get_map(location,
source="osm",
color="bw")
ggmap(gg, extent = "device", darken = c(0.9,"white")) +
geom_point(data = df, aes(x,y))
```
### Cropping
Crop out sf objects
```{r}
sf %>% st_crop(dd %>% filter(name == "Victoria"))
sf %>% st_intersection(dd %>% filter(name == "Victoria"))
```
Crop plot region to country border
```{r, cr1, eval = F}
ggplot() +
borders(regions = "Germany") +
geom_tile()
```
Mask/crop raster data
<!-- https://geocompr.robinlovelace.net/raster-vector.html -->
Crop raster/tiff to bbox
<!-- https://gis.stackexchange.com/questions/229356/crop-a-raster-file-in-r -->
```{r, cr2}
obj <- pathm # sf object
ras <- "raster.tiff" %>% raster # load raster
e <- as(obj %>% extent(), 'SpatialPolygons') # get bbox/extent as Sp
crs(e) <- "+proj=longlat +datum=WGS84 +no_defs" # add prj
r <- crop(ras, e) # crop raster to this bbox
r <- r %>% rasterToPoints() %>% as.data.frame # convert to df for plotting
colnames(r) <- c("x","y","z")
```
Get inverse mask (hole within sf obj)
```{r, cr3}
require(raster)
mask(sf1, sf2, inverse = T)
```
Crop multipolyon boundary to surround sf obj boundary and combine into one polygon
```{r, cr4}
dd %>% st_intersection(boundary_osm %>% st_boundary()) %>% st_cast("POLYGON")
# option 2
sf %>% st_union %>% st_cast("POLYGON") %>% st_boundary()
```
Shrink sf obj (reverse buffer)
<!-- geocompr.robinlovelace.net/geometric-operations -->
```{r, cr5}
# subtract centroid from geometry, then halve and reposition centroid
(sf$geometry - sf$geometry %>% st_centroid) / 2 + sf$geometry %>% st_centroid()
```
Displace sf obj
```{r, cr6}
# displace x by 0 and y by 500
sf_disp <- sf %>% st_geometry() + c(0, 500)
# plot using aes
ggplot() + geom_sf(aes(geometry = sf_disp))
```
Crop sf based on area
```{r,cr7}
sf %>% filter(st_area %>% as.numeric %in% sf %>% st_area %>% as.numeric %>% max)
# filter out polygons based on area
quant <- 0.3
sf %>% filter(st_area(.) > st_area(.) %>% quantile(quant)) # get polygons > 30% of all polygon areas
```
Make custom bbox
```{r, cr8}
require(ggmap)
lon <- 144.93
lat <- -37.79
ggmap::make_bbox(lon,lat,f = 0.5)
```
Crop satellite map to bbox
```{r, cr9}
# see blood gold for example
cropx <- c(10.5,23.4)
cropy <- c(-1.5,44.0)
ggplot() +
ggmap(basemap) + # sat map from google
scale_x_continuous(limits = cropx, expand = c(0,0)) +
scale_y_continuous(limits = cropy,expand = c(0,0))
```
Create concave polygon hull of multipoints
```{r, cr10}
require(concaveman)
sf %>% summarise() %>%
concaveman::concaveman(concavity = 1)
```
Crop raster
```{r, cr11}
require(raster)
r = raster(vals = rnorm(400), nrows=20, ncols=20, ext= extent(c(0, 20, 0, 20)))
p = Polygon(matrix(5, 5, 15, 12, 7, 16, 3, 10), ncol=2, byrow = T)
p = SpatialPolygons(list(Polygons(list(p), "p")))
r2 = mask(r,p)
plot(r2)
```
Get any city centroid, add buffer, then crop
```{r, cr12}
require(raster)
require(maps)
data(world.cities)
buff <- 2
country <- "Australia"
city <- "Melbourne"
# get centroid
bb <- world.cities %>%
filter(country.etc == country & name == city) %>%
select(long,lat) %>%
unlist %>%
st_point() %>%
st_buffer(buff)
# crop with polygon
sf %>% st_crop(bb)
# crop with bbox
sf %>% st_crop(bb %>% st_bbox() %>% st_as_sfc())
```
Crop one side of sf object
```{r}
# https://spencerschien.info/post/spatial_buffer/
sf_use_s2(FALSE) # set first to enable geos
sf %>% st_buffer(100, singleSide = T)
```
### Databases
Databases - maps, world data, natural earth, raster, DEM
```{r, d1, eval = F}
# country polygons and natural earth data - rivers/lakes, urban areas, etc
require(rnaturalearth)
# hires country polygons
devtools::install_github("ropensci/rnaturalearthhires")
require(rnaturalearthhires)
```
### Elevation
```{r}
require(elevatr)
pts <- c(-140.5, 35.6)
pts_buff <- pts %>% st_buffer(1*10^4) # create buffer around centroid
get_elev_raster(pts_buff, z = 12)
```
### Error fixing
Remove empty geometries
```{r, er1, eval = F}
# rm empty geos
# for "'spsample': error in evaluating the argument 'x' in selecting a method for function 'addAttrToGeom': empty geometries are not supported by sp classes: conversion failed"
sf %>% filter(!st_is_empty(.), drop = F)
sf %>% filter(is.na(st_dimension(.)) == F) # opt 2 to rm empty geos
```
Align sf objects with Google map satellite base map
```{r, er2, eval = F}
addy <- "Alice Springs, Northern Territory"
extent <- geocode(addy, output = "more") %>% pull(address)
maptype <- "satellite"
zoom <- 4
color <- "bw"
darken <- 0.3
# get google map
prj <- 3857 # set proj to match google map prj
base_map <- get_map(extent, maptype = maptype,color = color, zoom = zoom)
# function to fix the bbox to be in EPSG:3857
ggmap_bbox <- function(map) {
if (!inherits(map, "ggmap")) stop("map must be a ggmap object")
# Extract the bounding box (in lat/lon) from the ggmap to a numeric vector,
# and set the names to what sf::st_bbox expects:
map_bbox <- setNames(unlist(attr(map, "bb")),
c("ymin", "xmin", "ymax", "xmax"))
# Coonvert the bbox to an sf polygon, transform it to 3857,
# and convert back to a bbox (convoluted, but it works)
bbox_3857 <- st_bbox(st_transform(st_as_sfc(st_bbox(map_bbox, crs = 4326)), prj))
# Overwrite the bbox of the ggmap object with the transformed coordinates
attr(map, "bb")$ll.lat <- bbox_3857["ymin"]
attr(map, "bb")$ll.lon <- bbox_3857["xmin"]
attr(map, "bb")$ur.lat <- bbox_3857["ymax"]
attr(map, "bb")$ur.lon <- bbox_3857["xmax"]
map
}
map <- ggmap_bbox(base_map) # transform proj of sat map
# plot
map %>% ggmap(extent = "device", legend = "bottom", darken = c(0.5,"#FFFFFF"))
```
Plot sf data on Google maps basemap
```{r, er3, eval = F}
prj <- 3857 # set proj to match google map prj
map %>% ggmap(extent = "device", legend = "bottom", darken = c(0.5,"#FFFFFF")) +
geom_sf(data = sf %>% st_transform(prj), size = 0.05, inherit.aes = F) # include inherit.aes = F to show data
```
### GDB (`.gdb`/`.gdbtable`)
Read in `gdb` data
```{r}
fh <- "polygons.gdbtable" # "polygons.gdb"
fhl <- fh %>% st_layers() %>% .[[1]] # get layer name
sf <- fh %>% st_read(layer = fhl) # read in data using layer
```
### GPX
Read .gpx files (GPS track software/apps)
```{r, gpx1}
# option 1
gpx <- st_read("user.gpx", "track_points")
pathm <- gpx %>%
group_by(user_ID) %>% # get grouping variable
dplyr::summarize(do_union = F) %>%
st_cast("LINESTRING")
# option 2
pacman::p_load(XML,lubridate)
fd <- "/Volumes/Matt_timemachine/maptracks/2021/sep/sam/gpx/"
fh <- "day182.gpx"
gpx1 <- paste0(fd,fh) %>% # parse gpx file
htmlTreeParse(error = function(...) {}, useInternalNodes = T)
elev <- as.numeric(xpathSApply(gpx1, path = "//trkpt/ele", xmlValue))
times <- xpathSApply(gpx1, path = "//trkpt/time", xmlValue)
coord <- xpathSApply(gpx1, path = "//trkpt", xmlAttrs)
city_df <- tibble(lat = coord["lat",] %>% as.numeric(),
lon = coord["lon",] %>% as.numeric(),
elev = elev,
time = times %>% ymd_hms()
)
# elev profile
ggplot(data = city_df) +
geom_line(aes(time,elev)) +
scale_x_datetime(date_breaks = "6 hours"
# date_minor_breaks = "1 hour", # optional
# date_labels = "%M%D" # full month and year
)
# convert gpx coords to linestring
pathgpx <- city_df %>%
dplyr::select(lat,lon) %>%
as.matrix() %>% # convert points to linestring
st_linestring(dim = "XY") %>%
st_sfc(crs = 4326) %>% # convert sfg object to geometry
st_transform(crs = 4326) # then convert projection
```
Parse gpx data within kml
First manually convert file from '.kml' to '.gpx'
```{r, gpx2}
require(XML)
require(dplyr)
require(tidyr)
coord_id <- "//coord" # tag where lat/lon/elev data are located in file
gpx2 <- "data/full.gpx" %>%
htmlTreeParse(error = function(...) {}, useInternalNodes = T)
pathgpx <- xpathSApply(gpx2, path = coord_id, xmlValue) %>% # read coords (lon,lat,elev)
as.data.frame() %>%
tidyr::separate(col = ".",into = c("lon", "lat", "elev"), sep = " ", remove = T) %>% # separate char into individual values
mutate_all(as.numeric)
# timestamp
time_id <- "//when" # may vary with data
gpx2 <- "data/full.gpx" %>%
xpathSApply(gpx2, path = time_id, xmlValue) # get timestamp
```
### North arrow and scale bars
<!-- https://www.r-spatial.org/r/2018/10/25/ggplot2-sf.html -->
```{r, m2}
library("ggspatial")
ggplot(data = world) +
geom_sf() +
annotation_scale(location = "bl", width_hint = 0.5) +
annotation_north_arrow(location = "bl", which_north = "true",
pad_x = unit(0.75, "in"), pad_y = unit(0.5, "in"),
style = north_arrow_fancy_orienteering) +
coord_sf(xlim = c(-102.15, -74.12), ylim = c(7.65, 33.97))
# scale bar
p + ggspatial::annotation_scale(
location = "bl",
bar_cols = c(bg,fg),
line_width = 0.5,
pad_x = unit(1.5,"cm"),
pad_y = unit(1.5,"cm"),
text_col = fg, line_col = fg,
style = "ticks", # "bar"
width_hint = 0.1 # set scale to 10% of map
)
## Scale on map varies by more than 10%, scale bar may be inaccurate
```
```{r, m3}
# accessing coords in sf (complex)
# shp <- here::here("worldmaps","data","day14.shp") %>% readOGR()
# d <- shp@data # df vars
# bb <- shp@bbox #bbox
# ply <- shp@polygons # polygons
# plyl <- ply %>% purrr::map(ggplot2::fortify) # melt polygon class
# names(plyl) <- d$VARNAME_3 # get district name
# ggplot() +
# geom_polygon(data = ply_df[[600]],
# aes(long, lat))
# ply[[1]]@Polygons[[1]]@coords # works
# ply[[1]] %>% attr(which="Polygons") %>% purrr::map("coords") # works
```
<!-- ### Changing fonts in ggplot -->
<!-- https://stackoverflow.com/questions/34522732/changing-fonts-in-ggplot2 -->
### Projections
```{r, p1}
#list of proj
# https://proj.org/operations/projections/patterson.html
# https://spatialreference.org/ref/?search=albers&srtext=Search
require(mapdata,rnaturalworld)
###
d <- ne_countries(scale = "large",
type = "countries",
country = "Japan",
returnclass = "sf")
bb <- d$geometry %>% st_bbox()
# get current proj
d %>% st_crs() # /sf
d %>% crs() # /raster
# transform proj options
crsn <- 3995 # 3995 3033
plat <- 50
plon <- 0
prj <- paste0("+lat_0=",plat," +lon_0=",plon," +init=epsg:",crsn) # opt1
prj <- "+init=epsg:4326" # opt2
# transforming for diff data types
# da
ras@crs@projargs <- prj
ras %>% st_as_sf(coords = c("lon","lat"), crs = 4326) %>% # convert city_df to sp. NB need to set initial crs to one compatible with latlon coords, e.g. 4326
sf::st_transform(crs = prj) # now transform proj
dl %>% st_transform(prj) # shp
dt <- d %>% st_transform("+proj=utm +zone=19 +ellps=GRS80 +datum=NAD83")
dt <- d %>% st_transform(crsn)
# quartz()
p <- ggplot(data = d) +
geom_sf() +
coord_sf(crs = prj) # option 1
coord_sf(crs = st_crs(crsn)) # option 2
# proj in string format
prj <- projection(pathm) # get proj in string format
# site2 <- elevatr::get_elev_raster(city_df,
# z = zoom,
# prj = prj,
# expand = 3) %>% # get elev raster
# rasterToPoints() %>% # convert to df
# as.data.frame
# coerce projection
sf %>% st_set_crs(prj) %>% st_transform(prj2) # or use prj again to coerce uncooperative projections
```
Get projection info
```{r, p2}
# find proj
crs_codes = rgdal::make_EPSG() # get all espg code and info
crs_codes %>% filter(code == 27700) %>% pull # pull espg name and code
crs_codes[crs_codes$note %>% str_which("Austra"),"code"]
```
### KML/KMZ data
<!-- https://mitchellgritts.com/posts/load-kml-and-kmz-files-into-r/ -->
```{r, k1}
require(sf)
path <- "/data.kml" %>% sf::st_read() # single layer kml
path <- "/data.kml" %>% sf::st_layers() # multi layer kml
# for kmz, change .kmz to .zip, then unzip and read as kml
```
Save sf as kml/kmz
```{r}
# opt 1
st_write(sf, "test.kml", driver = "kml", delete_dsn = T)
# opt 2
require(rgdal)
writeOGR(sf, dsn = "sf.kml",
layer = "polygonWGS",
driver = KML)
```
### LIDAR
https://medium.com/@tobias.stalder.geo/visually-approach-lidar-surface-point-clouds-during-analysis-in-r-d2b0ffe21777
```{r}
library(rlas)
# 3d plotting of lidar data
devtools::install_github("AckerDWM/gg3D")
library(gg3D)
```
Convert raster to sf
```{r}
library(stars)
library(sf)
tifpath <- system.file("tif/L7_ETMs.tif", package = "stars")
tif <- read_stars(tifpath)
sf <- st_as_sf(tif)
```
### Conversions
Convert sp/sf/spdf data to data frame (fortify)
```{r, c1}
require(rworldmap)
require(broom)
d <- getMap(resolution = "high") # get world data
d_fort <- tidy(d, region = "NAME") # fortify
```
Convert sf geometry to df
```{r,c2}
require(sfheaders)
sf %>% sf_to_df
```
Convert points to linestring
```{r, c3}
inter_df <- rbind(df1,df2,df3) %>%
as.matrix() %>%
st_linestring(dim = "XY") %>% # convert points to single linestring
st_sfc(crs = 4326) # convert sfg object to geometry
# option 2
pathm <- city_df %>%
dplyr::select(lat,lon) %>%
as.matrix() %>% # convert points to linestring
st_linestring(dim = "XY") %>%
st_sfc(crs = 4326) %>% # convert sfg object to geometry
```
Convert each row in df to linestring
```{r, c4}
inter_df <- rbind(df1,df2,df3) %>%
st_as_sf(coords = c("lon","lat"), crs = 4326) %>%
st_geometry() %>%
st_cast("LINESTRING")
```
Replace coordinates in sf obj
```{r,c5}
sf_df <- sf %>% st_coordinates %>% data_frame # convert to df
sf_df[1:3,"Y"] <- c(10.1,10.2,10.3) # replace with new coords
sf <- sf_df[,c("X","Y")] %>% as.matrix() %>% st_linestring(dim = c("X","Y")) # convert back to sf
```
Flip XY coordinates
```{r}
sf %>% st_coordinates() %>% .[,c(2,1)]
```
Convert list of sf obj to sfc
```{r}
do.call(rbind, my_list)
```
Convert coordinates to text (for simple copy paste)
```{r}
bbc <- dd %>% filter(name %in% 'Netherlands')
bbc %>% st_centroid() %>% st_geometry() %>% st_as_text()
```
### Raster
Read in raster, change projection, and convert to matrix/df
```{r}
require(raster)
ras <- 'ras.tif' %>% raster()
prj <- ras %>% projection() # get proj
bb <- ras %>% extent() # get bbox
require(raster)
ras %>% raster() %>% crop(bb) %>%
rasterToPoints() %>% as.data.frame
require(rayshader)
ras %>% raster %>% crop(bb) %>%
raster_to_matrix()
require(terra)
ras %>% rast() %>% crop(bb)
# read in .adf files
require(rayshader)
"data.adf" %>% raster %>% raster_to_matrix %>% data.frame
```
Convert raster to various data stuctures
```{r, r1}
require(raster)
alt = getData('alt', country='CHE')
slope = terrain(alt, opt='slope')
aspect = terrain(alt, opt='aspect')
hill = hillShade(slope, aspect, 40, 270)
# raster to df
df <- alt %>% rasterToPoints() %>% as.data.frame() # terrain
df <- aspect %>% rasterToPoints() %>% as.data.frame() # aspect
df <- hill %>% rasterToPoints() %>% as.data.frame() # hillshade
# raster to sf
sf <- hill %>% rasterToPoints() %>% as.data.frame %>% st_as_sf(coords = c("x", "y"), crs = 4326)
bb <- sf %>% .[sf %>% nrow/2,] %>% st_buffer(5*10^4) # circle crop based on middle centroid
bb <- sf %>% .[sf %>% nrow/2,] %>% st_buffer(5*10^4) %>% st_bbox() # bbox crop
sf <- sf %>% st_crop(bb)
# raster to spdf
spp <- hill %>% as('SpatialPixelsDataFrame') %>% data.frame # ras to spdf to df
# plot
ggplot() +
geom_raster(data = df, aes(x,y, fill = layer)) # plot df
geom_sf(data = sf, aes(fill = layer, col =layer)) # plot sf
geom_sf(data = spp, aes(fill = layer, col =layer)) # plot spdf
```
Elevation profiles
<!-- https://rdrr.io/cran/topoDistance/man/topoProfile.html -->
```{r, r2}
pacman::p_load(topoDistance,elevatr)
# elevation raster (country tiles)
elevp <- getData('alt', country='FRA', mask = T)
elevp$FRA_msk_alt@crs # crs
elevp$FRA_msk_alt@extent # bbox
# elevation raster
elevp2 <- elevatr::get_elev_raster(city_df[,c("lon","lat")], # get elev raster
z = 3,
prj <- "+proj=longlat +datum=WGS84 +no_defs"
# expand = 3
) %>%
rasterToPoints() %>% as.data.frame
elevp2sf <- elevp2 %>% st_as_sf(coords = c("x","y"), crs = 4326) # df to sf
# elevation points (usa only)
elevp3 <- elevatr::get_elev_point(df,
prj <- "+init=epsg:4326")
elevp3_fort <- tidy(elevp3$elevation, region = "elevation") # fortify
# convert raster to diff classes
elevdf <- elevp %>% rasterToPoints() %>% as.data.frame # raster to df
elevdf <- elevp %>% rasterToPoints() %>% as.data.frame %>%
st_as_sf(coords = c("x","y"), crs = 4326) # raster to sp
# convert lines to elev profile
pts <- df[,c("lon","lat")] %>% as.matrix() %>% SpatialPoints() # df to points
elevpath <- topoDist(elevp,pts)
topoProfile(elevp,sl,pts = 100, type = "base") # generic elev profile plot
# plot
qplot(data = elevp2[1:10000,],x,layer,geom = "line")
```
Summarise raster layers
```{r,r3}
cellStats(raster,stat = "min",na.rm = T) # summarise raster layers
```
Read .tiff
```{r,r4}
require(raster)
dem1 <- "srtm_20_05.tif" %>% raster()
```
Decrease/increase raster resolution
```{r,r5}
ras %>% aggregate(fact = 3) # lower res by factor of 3
ras %>% disaggregate(fact = 3,
method = 'bilinear') # increase res by factor of 3
require(terra)
ras %>% disagg(3)
ras %>% aggregate(3)
ras %>% aggregate(c(2,3), fun = sum) # aggregate by diff factor for rows and cols plus change method
```
Match geometry/proj of raster from different sources
```{r, r6}
require(terra)
ras %>% res() # get resolution of raster
ras %>% resample(ras2) # resample ras2 to ras1 resolution
# change projection
ras %>% project("+proj=utm +zone=32")
```
Change resolution of raster
```{r}
require(raster)
res(ras)
xres(ras)
yres(ras)
res(ras) <- 1/120
res(ras) <- c(1/120, 1/60) # change res of x and y
```
Get zscale/elevation of raster
```{r}
require(geoviz)
ras %>% raster_zscale()
```