diff --git a/NAMESPACE b/NAMESPACE index b1d8c544d..2a0b0abc4 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,7 +1,7 @@ useDynLib(terra, .registration=TRUE) import(methods, Rcpp) exportClasses(SpatExtent, SpatRaster, SpatRasterDataset, SpatRasterCollection, SpatVector, SpatVectorProxy, SpatVectorCollection) -exportMethods("[", "[[", "!", "%in%", activeCat, "activeCat<-", "add<-", addCats, adjacent, all.equal, aggregate, allNA, align, animate, anyNA, app, area, Arith, approximate, as.bool, as.int, as.contour, as.lines, as.points, as.polygons, as.raster, as.array, as.data.frame, as.factor, as.list, as.logical, as.matrix, as.numeric, atan2, atan_2, autocor, barplot, blocks, boundaries, boxplot, buffer, cartogram, categories, cats, catalyze, clamp, clamp_ts, classify, clearance, cellSize, cells, cellFromXY, cellFromRowCol, cellFromRowColCombine, centroids, click, colFromX, colFromCell, colorize, coltab, "coltab<-", combineGeoms, compare, concats, Compare, compareGeom, contour, convHull, countNA, costDist, crds, cover, crop, crosstab, crs, "crs<-", datatype, deepcopy, delaunay, densify, density, depth, "depth<-", describe, diff, disagg, direction, distance, dots, draw, droplevels, elongate, emptyGeoms, erase, extend, ext, "ext<-", extract, expanse, fillHoles, fillTime, flip, focal, focal3D, focalCor, focalPairs, focalReg, focalCpp, focalValues, forceCCW, freq, gaps, geom, geomtype, global, gridDist, gridDistance, has.colors, has.RGB, hasMinMax, hasValues, hist, head, ifel, impose, init, image, inext, interpIDW, interpNear, inMemory, inset, interpolate, intersect, is.bool, is.int, is.lonlat, is.rotated, isTRUE, isFALSE, is.empty, is.factor, is.lines, is.points, is.polygons, is.related, is.valid, lapp, layerCor, levels, linearUnits, lines, Logic, varnames, "varnames<-", logic, longnames, "longnames<-", makeValid, mask, match, math, Math, Math2, mean, median, meta, merge, mergeLines, mergeTime, minmax, minRect, modal, mosaic, na.omit, not.na, NAflag, "NAflag<-", nearby, nearest, ncell, ncol, "ncol<-", nlyr, "nlyr<-", noNA, normalize.longitude, nrow, "nrow<-", nsrc, origin, "origin<-", pairs, panel, patches, perim, persp, plot, plotRGB, plet, RGB, "RGB<-", polys, points, predict, project, quantile, query, rangeFill, rapp, rast, rasterize, rasterizeGeom, rasterizeWin,readStart, readStop, readValues, rectify, regress, relate, removeDupNodes, res, "res<-", resample, rescale, rev, rcl, roll, rotate, rowFromY, rowColCombine, rowColFromCell, rowFromCell, sapp, scale, scoff, "scoff<-", sds, sort, sprc, sel, selectRange, setMinMax, setValues, segregate, selectHighest, set.cats, set.crs, set.ext, set.names, set.RGB, set.values, size, sharedPaths, shift, sieve, simplifyGeom, snap, sources, spatSample, split, spin, stdev, stretch, subset, subst, summary, Summary, svc, symdif, t, metags, "metags<-", tail, tapp, terrain, tighten, makeNodes, makeTiles, time, timeInfo, "time<-", text, trans, trim, units, union, "units<-", unique, unwrap, update, vect, values, "values<-", viewshed, voronoi, vrt, weighted.mean, where.min, where.max, which.lyr, which.min, which.max, which.lyr, width, window, "window<-", writeCDF, writeRaster, wrap, wrapCache, writeStart, writeStop, writeVector, writeValues, xmin, xmax, "xmin<-", "xmax<-", xres, xFromCol, xyFromCell, xFromCell, ymin, ymax, "ymin<-", "ymax<-", yres, yFromCell, yFromRow, zonal, zoom, cbind2, readRDS, saveRDS, unserialize, serialize) +exportMethods("[", "[[", "!", "%in%", activeCat, "activeCat<-", "add<-", addCats, adjacent, all.equal, aggregate, allNA, align, animate, anyNA, app, area, Arith, approximate, as.bool, as.int, as.contour, as.lines, as.points, as.polygons, as.raster, as.array, as.data.frame, as.factor, as.list, as.logical, as.matrix, as.numeric, atan2, atan_2, autocor, barplot, blocks, boundaries, boxplot, buffer, cartogram, categories, cats, catalyze, clamp, clamp_ts, classify, clearance, cellSize, cells, cellFromXY, cellFromRowCol, cellFromRowColCombine, centroids, click, colFromX, colFromCell, colorize, coltab, "coltab<-", combineGeoms, compare, concats, Compare, compareGeom, contour, convHull, countNA, costDist, crds, cover, crop, crosstab, crs, "crs<-", datatype, deepcopy, delaunay, densify, density, depth, "depth<-", describe, diff, disagg, direction, distance, dots, draw, droplevels, elongate, emptyGeoms, erase, extend, ext, "ext<-", extract, expanse, fillHoles, fillTime, flip, focal, focal3D, focalCor, focalPairs, focalReg, focalCpp, focalValues, forceCCW, freq, gaps, geom, geomtype, global, gridDist, gridDistance, has.colors, has.RGB, hasMinMax, hasValues, hist, head, ifel, impose, init, image, inext, interpIDW, interpNear, inMemory, inset, interpolate, intersect, is.bool, is.int, is.lonlat, is.rotated, isTRUE, isFALSE, is.empty, is.factor, is.lines, is.points, is.polygons, is.related, is.valid, k_means, lapp, layerCor, levels, linearUnits, lines, Logic, varnames, "varnames<-", logic, longnames, "longnames<-", makeValid, mask, match, math, Math, Math2, mean, median, meta, merge, mergeLines, mergeTime, minmax, minRect, modal, mosaic, na.omit, not.na, NAflag, "NAflag<-", nearby, nearest, ncell, ncol, "ncol<-", nlyr, "nlyr<-", noNA, normalize.longitude, nrow, "nrow<-", nsrc, origin, "origin<-", pairs, panel, patches, perim, persp, plot, plotRGB, plet, RGB, "RGB<-", polys, points, predict, project, quantile, query, rangeFill, rapp, rast, rasterize, rasterizeGeom, rasterizeWin,readStart, readStop, readValues, rectify, regress, relate, removeDupNodes, res, "res<-", resample, rescale, rev, rcl, roll, rotate, rowFromY, rowColCombine, rowColFromCell, rowFromCell, sapp, scale, scoff, "scoff<-", sds, sort, sprc, sel, selectRange, setMinMax, setValues, segregate, selectHighest, set.cats, set.crs, set.ext, set.names, set.RGB, set.values, size, sharedPaths, shift, sieve, simplifyGeom, snap, sources, spatSample, split, spin, stdev, stretch, subset, subst, summary, Summary, svc, symdif, t, metags, "metags<-", tail, tapp, terrain, tighten, makeNodes, makeTiles, time, timeInfo, "time<-", text, trans, trim, units, union, "units<-", unique, unwrap, update, vect, values, "values<-", viewshed, voronoi, vrt, weighted.mean, where.min, where.max, which.lyr, which.min, which.max, which.lyr, width, window, "window<-", writeCDF, writeRaster, wrap, wrapCache, writeStart, writeStop, writeVector, writeValues, xmin, xmax, "xmin<-", "xmax<-", xres, xFromCol, xyFromCell, xFromCell, ymin, ymax, "ymin<-", "ymax<-", yres, yFromCell, yFromRow, zonal, zoom, cbind2, readRDS, saveRDS, unserialize, serialize) S3method(cbind, SpatVector) S3method(rbind, SpatVector) diff --git a/R/Agenerics.R b/R/Agenerics.R index 3b270af9d..b4a7363e6 100644 --- a/R/Agenerics.R +++ b/R/Agenerics.R @@ -1,5 +1,7 @@ #if (!isGeneric("#")) { setGeneric("#", function(x, ...) standardGeneric("#")) } +if (!isGeneric("k_means")) {setGeneric("k_means", function(x, ...) standardGeneric("k_means"))} + if (!isGeneric("metags")) {setGeneric("metags", function(x, ...) standardGeneric("metags"))} if (!isGeneric("metags<-")) {setGeneric("metags<-", function(x, ..., value) standardGeneric("metags<-"))} diff --git a/R/kmeans.R b/R/kmeans.R new file mode 100644 index 000000000..0d478bead --- /dev/null +++ b/R/kmeans.R @@ -0,0 +1,35 @@ + +setMethod("k_means", signature(x="ANY"), + function(x, centers=3, ...) { + stats::kmeans(x, centers=centers, ...) + } +) + +setMethod("k_means", signature(x="SpatRaster"), + function(x, centers=3, ..., maxcell=1000000, filename="", overwrite=FALSE, wopt=list()) { + stopifnot(maxcell > 0) + if (ncell(x) <= maxcell) { + v <- na.omit(as.matrix(x)) + omit <- as.vector(attr(v, "na.action")) + km <- kmeans(v, centers=centers, ...) + r <- rast(x, nlyr=1) + if (is.null(omit)) { + values(r) <- km$cluster + } else { + r[-omit] <- km$cluster + } + if (filename != "") { + r <- writeRaster(r, filename=filename, overwrite=overwrite, wopt=wopt) + } + } else { + pkmeans = function(x, newdata) { + apply(newdata, 1, function(i) which.min(colSums((t(x$centers) - i)^2))) + } + v <- na.omit(spatSample(x, maxcell, "regular")) + km <- kmeans(v, centers=centers, ...) + r <- predict(logo, km, fun=pkmeans, na.rm=TRUE, filename=filename, overwrite=overwrite, wopt=wopt) + } + r + } +) + diff --git a/man/k_means.Rd b/man/k_means.Rd new file mode 100644 index 000000000..085145611 --- /dev/null +++ b/man/k_means.Rd @@ -0,0 +1,41 @@ +\name{k_means} + +\alias{k_means} + +\alias{k_means,ANY-method} +\alias{k_means,SpatRaster-method} + +\title{k_means} + +\description{ +Compute kmeans clusters for a SpatRaster +} + +\usage{ +\S4method{k_means}{SpatRaster}(x, ..., filename="", overwrite=FALSE, wopt=list()) +} + +\arguments{ + \item{x}{SpatRaster} + \item{...}{additional arguments passed to \code{\link[stats]{k_means}}, such as the required argument \code{centers}} + \item{filename}{character. Output filename (ignored if \code{as.raster=FALSE}} + \item{overwrite}{logical. If \code{TRUE}, \code{filename} is overwritten} + \item{wopt}{list with additional arguments for writing files as in \code{\link{writeRaster}}} +} + +\value{ +SpatRaster +} + +\seealso{ \code{\link[stats]{k_means}} +} + +\examples{ +f <- system.file("ex/logo.tif", package = "terra") +r <- rast(f) +km <- k_means(r, centers=5) +km +} + +\keyword{spatial} +