Search code examples
rdplyrr-rastermagrittr

Combine (or replace) indexing with dplyr filtering (to plot raster)


I have a data.frame/tibble with once variable that is a list of raster bricks, e.g, a:

library(dplyr)
library(raster)

x <- matrix(
  data = rnorm(100, 0, 1),
  nrow = 10,
  ncol = 10
) %>%
  raster

y <- matrix(
  data = rnorm(100, 0, 1),
  nrow = 10,
  ncol = 10
) %>%
  raster

z <- matrix(
  data = rnorm(100, 0, 1),
  nrow = 10,
  ncol = 10
) %>%
  raster

a <- tribble(
  ~thing, ~map,
  "b", brick(x, y),
  "c", brick(z, y),
  "d", brick(x, z),
  "e", brick(y, z),
)

a
#> # A tibble: 4 x 2
#>   thing map       
#>   <chr> <list>    
#> 1 b     <RstrBrck>
#> 2 c     <RstrBrck>
#> 3 d     <RstrBrck>
#> 4 e     <RstrBrck>

I want to pull out some rasters from within the bricks to plot, e.g.:

plot(a$map[[3]][[2]])

But rather than index to the row, I want to use dplyr::filter to select the appropriate row to plot, and I can get to the appropriate column using pull but I can't get my head around how to get then to the appropriate raster within the brick object in order to plot it, short of assigning it as a new object and then indexing the new object. What I want to do is something like the below (which fails):


a %>%
  filter(thing == "d") %>%
  pull(map)[[2]] %>%
  plot
#> Error in pull(map): object 'map' not found

Solutions?

Created on 2021-02-03 by the reprex package (v0.3.0)


Solution

  • Try this

    a %>%
      filter(thing == "d") %>%
      pull(map) %>%
      .[[1]] %>% 
      .[[2]] %>% 
      plot
    
    a %>%
      filter(thing == "d") %>%
      .$map %>% 
      .[[1]] %>% 
      .[[2]] %>% 
      plot
    

    Note that pull(map) is equivalent to .$map.