Search code examples
rimageraster

Exporting image file direcly from R based on data frame


I have this following data frame in R:

df <- data.frame(a = c(0, 0, 1, 1),
                 b = c(0, 1, 0, 1),
                 col = c("red", "green", "green", "yellow"))

I am interested in exporting a raster image file (png, tif, etc) that will contain one pixel for each entry in the data frame, with the appropriate color. For the above example there will be a 2 by 2 image file that looks like this:

enter image description here

I have a feeling that the raster package might be useful, but as I understand it can only export geospatial raster image types and not plain images.


Solution

  • This works, using the tiff package:

    library(tiff)
    
    df <- data.frame(a = c(0, 0, 1, 1),
                     b = c(0, 1, 0, 1),
                     col = c("red", "green", "green", "yellow"))
    
    mina <- min(df$a)
    minb <- min(df$b)
    maxa <- max(df$a)
    maxb <- max(df$b)
    
    colarray <- array(data = NA,
                      dim = c(maxb - minb + 1,
                              maxa - mina + 1,
                              3))
    
    for (k in 1:nrow(df))
    {
      colarray[df[k, 2] - minb + 1,
               df[k, 1] - mina + 1,
               ] <- col2rgb(df[k, 3]) / 255
    }
    writeTIFF(colarray, "res.tif", compression = "LZW")
    

    It could be a bit more succinct, but this works better for cases where the x&y coordinates are not necessarily 0 to n.

    This will work the same using related packages such as png.