title: R: Creating list of png rasters, reading into grid.raster
body: <p>This post is related to a <a href="https://stackoverflow.com/questions/36133374/custom-legend-with-imported-images">question</a> I asked a couple days ago, and specifically to this <a href="https://stackoverflow.com/a/36144865/4731430">post</a> (from which I borrowed the code below). I felt it warranted a new question because this is a new issue.</p>
  
  <p>I am trying to graph in ggplot2 with custom images for geom_point, then paste those images into the legend. However, when I put the image rasters into a list, and reference elements of that list in grid.raster it throws an error. Is there are way to store png rasters in a list so they can be called from grid.raster later? Here's an example...</p>
  
  <pre><code>library(png)
  library(ggplot2)
  library(grid)
  
  # Get image
  img &lt;- readPNG(system.file("img", "Rlogo.png", package="png"))
  
  # Grab online image
  url &lt;- "https://www.rstudio.com/wp-content/uploads/2014/06/RStudio-Ball.png"
  destfile &lt;- "myfile.png"
  r_studio &lt;- download.file(url, destfile, mode="wb")
  r_studio &lt;- readPNG("myfile.png")
  
  # Put images in list    
  image_list &lt;- list(img, r_studio)
  
  # Plot
  p = ggplot(mtcars, aes(mpg, disp, colour = factor(vs))) + 
    geom_point() +
    theme(legend.key.size = unit(1, "cm"))
  
  # Get ggplot grob
  gt = ggplotGrob(p)
  grid.newpage()
  grid.draw(gt)
  
  
  # Search using regular expressions
  Tree = as.character(current.vpTree())
  pos = gregexpr("\\[key.*?\\]", Tree)
  match = unlist(regmatches(Tree, pos))
  
  match = gsub("^\\[(key.*?)\\]$", "\\1", match) # remove square brackets
  match = match[!grepl("bg", match)]  # removes matches containing bg
  
  # Loop through image list. Change the legend keys to images
  for(i in 1:2){
   downViewport(match[i])
   grid.rect(gp=gpar(col = NA, fill = "white"))
   grid.raster(image_list[i], interpolate=FALSE)
   upViewport(0) 
  }
  </code></pre>
  
  <p>When I run this last loop I get the following error</p>
  
  <pre><code>Error in UseMethod("as.raster") : 
   no applicable method for 'as.raster' applied to an object of class "list" 
  </code></pre>
  
  <p>I noticed that putting the images into a list changes the type from double to list, so I'm guessing this has something to do with it. </p>
  
  <pre><code>typeof(img)
  [1] "double"
  typeof(image_list[1])
  [1] "list"
  </code></pre>