Created
October 31, 2019 07:38
-
-
Save statnmap/a3eb564d06dee47f2d83eceac4212881 to your computer and use it in GitHub Desktop.
Transform multiple layer dataframe raster into stack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(raster) | |
# remotes::install_github("statnmap/cartomisc") | |
library(cartomisc) | |
library(dplyr) | |
library(purrr) | |
# Create original raster | |
fn <- system.file("external/test.grd", package="raster") | |
s <- stack(fn, fn) | |
# Transform as data.frame | |
s_df <- cartomisc::gplot_data(s) %>% | |
rename(year = variable) | |
s_df | |
#> # A tibble: 18,400 x 4 | |
#> x y value year | |
#> <dbl> <dbl> <dbl> <fct> | |
#> 1 178420 333980 NA test.1 | |
#> 2 178460 333980 NA test.1 | |
#> 3 178500 333980 NA test.1 | |
#> 4 178540 333980 NA test.1 | |
#> 5 178580 333980 NA test.1 | |
#> 6 178620 333980 NA test.1 | |
#> 7 178660 333980 NA test.1 | |
#> 8 178700 333980 NA test.1 | |
#> 9 178740 333980 NA test.1 | |
#> 10 178780 333980 NA test.1 | |
#> # … with 18,390 more rows | |
# Transform from xyzt into raster | |
s_df_raster <- s_df %>% | |
group_split(year) %>% | |
map(~rasterFromXYZ(.x[,c("x", "y", "value")])) %>% | |
stack() | |
names(s_df_raster) <- unique(s_df$year) | |
s_df_raster | |
#> class : RasterStack | |
#> dimensions : 115, 80, 9200, 2 (nrow, ncol, ncell, nlayers) | |
#> resolution : 40, 40 (x, y) | |
#> extent : 178400, 181600, 329400, 334000 (xmin, xmax, ymin, ymax) | |
#> crs : NA | |
#> names : test.1, test.2 | |
#> min values : 128.434, 128.434 | |
#> max values : 1805.78, 1805.78 | |
# <sup>Created on 2019-10-31 by the [reprex package](https://reprex.tidyverse.org) (v0.2.1)</sup> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment