[GIS] Convert raster outputs to data.frame format

rraster

I've moved over to version 2 of the lidR package. In previous versions, the output of grid_metrics was a data.frame. In version 2.0, the outputs are stored in raster format. I have additional code, such as running a PCA that works with the metrics in a data.frame.

Is there a suggested method for converting the raster products back into a data.frame?

Best Answer

Make a sample raster:

> r1 = raster(matrix(1:12,3,4))

make two more and make a stack with names:

> r2 = r1 + 1
> r3 = r1 + 2
> s = stack(list(r1=r1, r2=r2, r3=r3))
> names(s)
[1] "r1" "r2" "r3"

Now convert to data frame:

> as.data.frame(s, xy=TRUE)
       x         y r1 r2 r3
1  0.125 0.8333333  1  2  3
2  0.375 0.8333333  4  5  6
3  0.625 0.8333333  7  8  9
4  0.875 0.8333333 10 11 12
5  0.125 0.5000000  2  3  4
6  0.375 0.5000000  5  6  7
7  0.625 0.5000000  8  9 10
8  0.875 0.5000000 11 12 13
9  0.125 0.1666667  3  4  5
10 0.375 0.1666667  6  7  8
11 0.625 0.1666667  9 10 11
12 0.875 0.1666667 12 13 14
> 

Note that rasterToPoints does a similar thing, but returns a matrix:

> rasterToPoints(s)
          x         y r1 r2 r3
 [1,] 0.125 0.8333333  1  2  3
 [2,] 0.375 0.8333333  4  5  6
 [3,] 0.625 0.8333333  7  8  9

but if all values are NA that point is omitted from the output. as.data.frame preserves all points:

Make first pixel NA in all layers:

> s[[1]][1,1]=NA;s[[2]][1,1]=NA;s[[3]][1,1]=NA

Then:

> head(rasterToPoints(s))
         x         y r1 r2 r3
[1,] 0.375 0.8333333  4  5  6
[2,] 0.625 0.8333333  7  8  9
[3,] 0.875 0.8333333 10 11 12
[4,] 0.125 0.5000000  2  3  4
[5,] 0.375 0.5000000  5  6  7
[6,] 0.625 0.5000000  8  9 10

compare:

> head(as.data.frame(s,xy=TRUE))
      x         y r1 r2 r3
1 0.125 0.8333333 NA NA NA
2 0.375 0.8333333  4  5  6
3 0.625 0.8333333  7  8  9
4 0.875 0.8333333 10 11 12
5 0.125 0.5000000  2  3  4
6 0.375 0.5000000  5  6  7
Related Question