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?
1 Answer 1
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.
-
1Matrices 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– Farid Cheraghi2016年09月18日 10:28:14 +00:00Commented Sep 18, 2016 at 10:28 -
You cannot get rid of row names in data.frame objects.Jeffrey Evans– Jeffrey Evans2016年09月19日 00:54:22 +00:00Commented Sep 19, 2016 at 0:54