Search code examples
rlistdataframeraster

R: Convert list of data.frames to list of raster


Let's say I have a list of data.frames:

a1<-as.data.frame(1:9)
a2<-as.data.frame(2:10)
a3<-as.data.frame(3:11)

a.list<-list(a1,a2,a3)

Now I want to convert each data.frame of the list into a 3 by 3 raster layer. The layers should be in a list afterwards.

I tried to perform this with lapply, but can't really tell what the problem is:

r.list<-lapply(a.list, raster(nrows=3, ncols=3))

Solution

  • You probably need to convert your dataframes to matrices first. Exploit the fact that you have 1-column data frames to convert them to vectors and then use the matrix function:

    > rl = lapply(a.list, function(X) raster(matrix(X[,1],nrow=3)))
    > rl[[1]]
    class       : RasterLayer 
    dimensions  : 3, 3, 9  (nrow, ncol, ncell)
    resolution  : 0.3333333, 0.3333333  (x, y)
    extent      : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
    coord. ref. : NA 
    data source : in memory
    names       : layer 
    values      : 1, 9  (min, max)
    

    You may want to make sure the rasters are being constructed row-wise or column-wise - use the byrow arg to matrix to adjust this, or transpose the matrix or otherwise arrange it.