| 1 |
#' @templateVar class kmeans |
| 2 |
#' @template title_desc_tidy |
| 3 |
#' |
| 4 |
#' @param x A `kmeans` object created by [stats::kmeans()]. |
| 5 |
#' @param col.names Dimension names. Defaults to the names of the variables |
| 6 |
#' in x. Set to NULL to get names `x1, x2, ...`. |
| 7 |
#' @template param_unused_dots |
| 8 |
#' |
| 9 |
#' @evalRd return_tidy("size", "withinss", "cluster") |
| 10 |
#' |
| 11 |
# skip running examples - occasionally over CRAN check time limit |
| 12 |
#' @examplesIf FALSE |
| 13 |
#' |
| 14 |
#' library(cluster) |
| 15 |
#' library(modeldata) |
| 16 |
#' library(dplyr) |
| 17 |
#' |
| 18 |
#' data(hpc_data) |
| 19 |
#' |
| 20 |
#' x <- hpc_data[, 2:5] |
| 21 |
#' |
| 22 |
#' fit <- pam(x, k = 4) |
| 23 |
#' |
| 24 |
#' tidy(fit) |
| 25 |
#' glance(fit) |
| 26 |
#' augment(fit, x) |
| 27 |
#' |
| 28 |
#' @aliases kmeans_tidiers |
| 29 |
#' @export |
| 30 |
#' @seealso [tidy()], [stats::kmeans()] |
| 31 |
#' @family kmeans tidiers |
| 32 |
tidy.kmeans <- function(x, col.names = colnames(x$centers), ...) { |
| 33 |
if (is.null(col.names)) { |
| 34 |
col.names <- paste0("x", 1:ncol(x$centers)) |
| 35 |
} |
| 36 |
ret <- as.data.frame(x$centers) |
| 37 |
colnames(ret) <- col.names |
| 38 |
ret$size <- x$size |
| 39 |
ret$withinss <- x$withinss |
| 40 |
ret$cluster <- factor(seq_len(nrow(ret))) |
| 41 |
as_tibble(ret) |
| 42 |
} |
| 43 |
|
| 44 |
|
| 45 |
#' @templateVar class kmeans |
| 46 |
#' @template title_desc_augment |
| 47 |
#' |
| 48 |
#' @inherit tidy.kmeans params examples |
| 49 |
#' @template param_data |
| 50 |
#' |
| 51 |
#' @evalRd return_augment( |
| 52 |
#' ".cluster", |
| 53 |
#' .fitted = FALSE, |
| 54 |
#' .resid = FALSE |
| 55 |
#' ) |
| 56 |
#' |
| 57 |
#' @export |
| 58 |
#' @seealso [augment()], [stats::kmeans()] |
| 59 |
#' @family kmeans tidiers |
| 60 |
augment.kmeans <- function(x, data, ...) { |
| 61 |
check_ellipses("newdata", "augment", "kmeans", ...) |
| 62 |
|
| 63 |
# kmeans allows for input matrices without column names, |
| 64 |
# so add them in the same way that fix_data_frame() would have |
| 65 |
if (inherits(data, "matrix") & is.null(colnames(data))) { |
| 66 |
colnames(data) <- paste0("X", 1:ncol(data)) |
| 67 |
} |
| 68 |
|
| 69 |
as_augment_tibble(data) |> |
| 70 |
mutate(.cluster = as.factor(!!x$cluster)) |
| 71 |
} |
| 72 |
|
| 73 |
|
| 74 |
#' @templateVar class kmeans |
| 75 |
#' @template title_desc_glance |
| 76 |
#' |
| 77 |
#' @inherit tidy.kmeans params examples |
| 78 |
#' |
| 79 |
#' @evalRd return_glance("totss","tot.withinss", "betweenss", "iter") |
| 80 |
#' |
| 81 |
#' @export |
| 82 |
#' @seealso [glance()], [stats::kmeans()] |
| 83 |
#' @family kmeans tidiers |
| 84 |
glance.kmeans <- function(x, ...) { |
| 85 |
as_tibble(x[c("totss", "tot.withinss", "betweenss", "iter")]) |
| 86 |
} |