Skip to content

Instantly share code, notes, and snippets.

@statnmap
Created October 31, 2019 07:38

Revisions

  1. statnmap created this gist Oct 31, 2019.
    47 changes: 47 additions & 0 deletions df_to_stack.R
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    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>