1

I have created a data frame which I need to convert to an image. This particular data frame is measured 174, 209, 36366 (nrow, ncol, ncell) respectively. This data frame is created and stored in R and I dont know how to export it from R or create a raster layer (of the same dimensions) for imaging from it. It is effectively a table of pixel values. Can anybody help?

6

Coerce the data.frame to a matrix and then use the raster function in the raster library to convert the matrix to a raster. This type of object should be in a matrix format to begin with because you save the overhead of row and column names, which data.frame objects must have.

library(raster)

nr = 174
nc = 209
x <- data.frame()
for(i in 1:nr) { x <- rbind(x, runif(nc) ) }

x <- as(x, "matrix")
  dim(x)

x <- raster(x)
  class(x)
  plot(x) 

From here you can use writeRaster to export to a variety of formats.

  • 1
    Matrices have also rownames and colnames. one can strip out colnames from dataframes i.e. colnames(df) <- NULL. The point is raster only accepts matrix beside other spatial format. – Farid Cheraghi Sep 18 '16 at 10:28
  • You cannot get rid of row names in data.frame objects. – Jeffrey Evans Sep 19 '16 at 0:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.