#' Normalize GRF functions
#'
#' This function ensures that each function in the specified GRF object is between 0 and 1 in value, and that the functions sum to 1 at every location.
#' This is useful when the functions are used to compute a weighted mean of multiple layers.
#'
#' @param grf.object A GRF object generated by \code{\link{generate.grf.object}}.
#' @param scaling.method Specifices whether the functions should be rescaled between 0 and 1 by a min-max scaling (\code{scaling.method = "minmax"}), or a uniform scaling (\code{scaling.method = "uniform"}).
#'
#' @note The properties above (summing to 1 and between 0 and 1 in value) only hold in the grid locations.
#' When interpolating in arbitrary locations, small deviations will occur.
#'
#' @return A normalized GRF object.
#'
#' @examples
#' library(GRFics)
#' library(ggplot2)
#' grf.object = generate.grf.object(-1, 1, -1, 1, 100, 100,
#' num.functions = 2)
#' grf.object = normalize.grf.functions(grf.object)
#'
#'
#' function.1.df = get.function.df(grf.object, function.numbers = 1)
#' function.2.df = get.function.df(grf.object, function.numbers = 2)
#' sum.df = data.frame(x = function.1.df$x,
#' y = function.1.df$y,
#' z = function.1.df$z + function.2.df$z,
#' name = "Sum")
#' comparison.df = rbind(function.1.df, function.2.df, sum.df)
#' ggplot()+
#' geom_raster(data = comparison.df, aes(x = x, y = y, fill = z))+
#' facet_wrap(vars(name))+
#' coord_fixed()
#'
#' @export
#' @author Mathias Isaksen \email{mathiasleanderi@@gmail.com}
normalize.grf.functions = function(grf.object, scaling.method = "uniform") {
num.functions = length(grf.object$functions)
function.matrix = matrix(NA, nrow = nrow(grf.object$grid), ncol = num.functions)
for (i in 1:num.functions) {
if (scaling.method == "uniform") {
function.ecdf = ecdf(grf.object$functions[[i]])
grf.object$functions[[i]] = function.ecdf(grf.object$functions[[i]])
} else if (scaling.method == "minmax") {
grf.object$functions[[i]] = standardize(grf.object$functions[[i]])
} else {
stop("Invalid value for scaling.method specified.")
}
function.matrix[, i] = grf.object$functions[[i]]
}
function.matrix = t(apply(function.matrix, 1, function(x) x/sum(x)))
for (i in 1:num.functions) {
grf.object$functions[[i]] = function.matrix[, i]
}
return(grf.object)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.