如何在 R 中使用“hclust”作为函数调用

Posted

技术标签:

【中文标题】如何在 R 中使用“hclust”作为函数调用【英文标题】:How to use 'hclust' as function call in R 【发布时间】:2013-12-19 01:15:38 【问题描述】:

我尝试通过以下方式将聚类方法构造为函数:

mydata <- mtcars

# Here I construct hclust as a function
hclustfunc <- function(x) hclust(as.matrix(x),method="complete")

# Define distance metric
distfunc <- function(x) as.dist((1-cor(t(x)))/2)

# Obtain distance
d <- distfunc(mydata)

# Call that hclust function
fit<-hclustfunc(d)

# Later I'd do
# plot(fit)

但为什么会出现以下错误:

Error in if (is.na(n) || n > 65536L) stop("size cannot be NA nor exceed 65536") : 
  missing value where TRUE/FALSE needed

正确的做法是什么?

【问题讨论】:

【参考方案1】:

请阅读您使用的功能的帮助。 ?hclust 很清楚第一个参数 d 是一个相异对象,而不是矩阵:

Arguments:

       d: a dissimilarity structure as produced by ‘dist’.

更新

由于 OP 现在已经更新了他们的问题,所以需要的是

hclustfunc <- function(x) hclust(x, method="complete")
distfunc <- function(x) as.dist((1-cor(t(x)))/2)
d <- distfunc(mydata)
fit <- hclustfunc(d)

原创

你想要的是

hclustfunc <- function(x, method = "complete", dmeth = "euclidean")     
    hclust(dist(x, method = dmeth), method = method)

然后

fit <- hclustfunc(mydata)

按预期工作。请注意,您现在可以将相异系数方法作为dmeth 和聚类方法传递。

【讨论】:

以上是关于如何在 R 中使用“hclust”作为函数调用的主要内容,如果未能解决你的问题,请参考以下文章