In order to perform a kmean cluster analysis on large raster datasets I am attempting to convert my RasterBrick
object into a big.matrix
object using the brick
function, but when I read the .grd file back into R
all the information is lost.
library(raster)
library(bigmemory)
library(biganalytics)
#initialize raster
one <- raster(matrix(rnorm(400), 20, 20))
two <- raster(matrix(rnorm(400), 20, 20))
three <- raster(matrix(rnorm(400), 20, 20))
#save brick object as .grd file
brick(one, two, three, filename = "test")
#read .grd file in as big.matrix
big_matrix <- as.big.matrix("test.grd", type = "double")
#check dimensions
dim(big_matrix)
#perform kmeans
bigkmeans(big_matrix, 3)
I can see the the .grd and .gri files in my directory, but I can't figure out how to read them back in, or how to feed the .grd file into bigkmean
function. Any idea how I might do this?
Example data
library(raster)
library(bigmemory)
b <- brick(system.file("external/rlogo.grd", package="raster"))
If the file is not that large, you could do
x <- as.big.matrix(values(b))
Otherwise, here is a function you can use.
r2bm <- function(from, filename="") {
b <- big.matrix(ncell(from), nlayers(from), backingfile=filename )
nc <- ncol(from)
tr <- blockSize(from)
for (i in 1:tr$n) {
start <- ((tr$row[i]-1) * nc) + 1
end <- start + (tr$nrows[i] * nc) - 1
b[start:end, ] <- getValues(from, row=tr$row[i], nrows=tr$nrows[i])
}
b
}
Now use it
y <- r2bm(b, "bg.dat")