【问题标题】:How does the begining of cluster::pam works?cluster::pam 的开头是如何工作的?
【发布时间】:2018-04-02 02:48:07
【问题描述】:

我正在研究 cluster 包的 pam 函数,其中的某些内容似乎很尴尬:该函数缺少对象。让我解释一下我的意思。

这是cluster::pam在终端中获取的函数代码示例。

function (x, k, diss = inherits(x, "dist"), metric = "euclidean", 
          medoids = NULL, stand = FALSE, cluster.only = FALSE, do.swap = TRUE, 
          keep.diss = !diss && !cluster.only && n < 100, keep.data = !diss && 
            !cluster.only, pamonce = FALSE, trace.lev = 0) 
{
  stopifnot(length(cluster.only) == 1, length(trace.lev) == 
              1)
  nMax <- 65536
  if ((diss <- as.logical(diss))) {
    if (anyNA(x)) 
      stop("NA values in the dissimilarity matrix not allowed.")
    if (data.class(x) != "dissimilarity") {
      if (!is.null(dim(x))) {
        x <- as.dist(x)
      }
      else {
        if (!is.numeric(x) || is.na(n <- sizeDiss(x))) 
          stop("'x' is not and cannot be converted to class \"dissimilarity\"")
        attr(x, "Size") <- n
      }
      class(x) <- dissiCl
      if (is.null(attr(x, "Metric"))) 
        attr(x, "Metric") <- "unspecified"
    }
    if (keep.data) 
      stop("Cannot keep data when 'x' is a dissimilarity!")
    n <- attr(x, "Size")
    if (n > nMax) 
      stop(gettextf("have %d observations, but not more than %d are allowed", 
                    n, nMax))
    dv <- x[lower.to.upper.tri.inds(n)]
    dv <- c(0, dv)
    storage.mode(dv) <- "double"
    jp <- 1
    mdata <- FALSE
    ndyst <- 0

... it continues

当通过在 Global Env 中创建我自己的函数在包外运行它时,它指责对象 dissiCl 没有创建。所以,我想知道为什么当以cluster::pam 运行该函数时,它并没有指责该对象丢失。

您可以通过运行这两个函数来看到这种差异。 myPam 是在 Global Env 中创建的函数,只需处理来自 cluster::pam 的代码即可。

myPam(dist(mtcars), 12)
cluster::pam(dist(mtcars), 12)

另外,谁能解释一下我怎么可能有这种情况,它在函数代码中,如 TRUEdata.class(x) != "dissimilarity"

当将x 输入为(例如)dist(myBase) 时,该对象的类为diss。但是,如何创建类 dissimilarity 的对象?

【问题讨论】:

    标签: r cluster-analysis packages


    【解决方案1】:

    dissiCl 是一个非导出对象,它来自您加载 cluster 时附加的命名空间。 cluster::pam 函数正在访问它。如果您愿意,请在您的函数中使用cluster:::dissiCl 作为dissiCl

    您也会在该函数中的其他对象遇到这个问题。如果您尝试在不运行 library(cluster) 的情况下运行它。您可以对所有对象进行查找/替换,在每个导出的对象之前添加cluster::,并为每个未导出的对象添加cluster:::

    您可以使用相同的策略将对象转换为类"dissimilarity"。如果它已经属于diss 类,或者属于"dist" 类,我建议使用pam 强制它的方式。只需设置class(myBase) &lt;- cluster:::dissiCl

    您可能正在使用属于 dist 类而不是 diss 的对象(dist() 返回类 dist 的对象),但看起来这应该不是问题。

    【讨论】:

    • 有没有办法将对象加载为dissiCl,因此不必添加前缀cluster:::?使用 library(cluster) 似乎只影响函数上命名空间运算符的需要,而不影响 variables
    • 这是包开发者的设计决定。 library(cluster) 准确加载设计者决定导出的那些函数和变量。他/她决定不导出dissiCl,因此您只能使用::: 运算符获取它。 library 或其他方法中没有任何选项可以一次性加载所有未导出的对象,因此您只能使用 :::
    猜你喜欢
    • 1970-01-01
    • 2017-11-12
    • 2019-11-01
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    相关资源
    最近更新 更多