Search code examples
rraster

Extract all values as one column of a raster?


If I have this stack with three layers.

     library(terra)  
     y <- rast(ncol=10, nrow=10, nlyr=3, vals=rep(1:3, each=100))

I would like to extract the values in one column as follows:

 pixels 1 from lyr.1
 pixels 1 from lyr.2
 pixels 1 from lyr.3
 pixels 2 from lyr.1
 pixels 2 from lyr.2
 pixels 2 from lyr.3

etc


Solution

  • You can convert the SpatRaster to a data frame with the cell index and then manipulate it (e.g. with tidyverse) to suit your needs:

    library(terra)  
    #> terra 1.5.34
    y <- rast(ncol=10, nrow=10, nlyr=3, vals=rep(1:3, each=100))
    
    df <- as.data.frame(y, cells=TRUE)
    
    # Tidyverse approach
    library(tidyverse)
    final_df <- df %>% pivot_longer(cols=c(lyr.1, lyr.2, lyr.3),
                        names_to = "layer") %>%
      rename(pixel = cell)
    
    final_df
    #> # A tibble: 300 x 3
    #>    pixel layer value
    #>    <int> <chr> <int>
    #>  1     1 lyr.1     1
    #>  2     1 lyr.2     2
    #>  3     1 lyr.3     3
    #>  4     2 lyr.1     1
    #>  5     2 lyr.2     2
    #>  6     2 lyr.3     3
    #>  7     3 lyr.1     1
    #>  8     3 lyr.2     2
    #>  9     3 lyr.3     3
    #> 10     4 lyr.1     1
    #> # ... with 290 more rows
    

    Created on 2022-07-12 by the reprex package (v2.0.1)