#' Fitting an object of class kMeans
#'
#' Extract the fitted values from a data set modeled by \code{kMeansLloyd}.
#' @param object an object of class \code{"kMeans"}. Usually, the result of
#' \code{kMeansLloyd}.
#' @param method character: either \code{"centroids"} or \code{"cluster"}. If
#' \code{"centroids"} leads to \code{fitted} returning the cluster centroids
#' one for each observation, if \code{"cluster"} causes \code{fitted} to
#' return a vector of class assignments.
#' @param ... other arguments.
#' @export
#'
#' @examples
#' # create example data set
#' X <- rbind(matrix(rnorm(50, sd = 0.5), ncol = 2),
#' matrix(rnorm(50, mean = 1, sd = 0.5), ncol = 2))
#'
#' # perform k-means algorithm
#' result <- kMeansLloyd(x = X, centroids = 2, nStart = 2)
#'
#' # fit the result
#' # centroids
#' fitted(result, method = "centroids")
#' # cluster
#' fitted(result, method = "cluster")
#'
#' # compute cluster centroids "fitted" to each observation:
#' fittedX <- fitted(result)
#' residX <- X - fittedX
#' @seealso \code{\link{kMeansLloyd}}
fitted.kMeans <- function(object, method = c("centroids", "cluster"), ...) {
method <- match.arg(method)
if (method == "centroids") {
res <- object$centroids[object$cluster, , drop = FALSE]
rownames(res) <- object$cluster
res
} else {
object$cluster
}
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.