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

nev*_*int 17 r cluster-analysis function-calls hclust

我试着通过以下方式构建聚类方法:

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)
Run Code Online (Sandbox Code Playgroud)

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

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

什么是正确的方法呢?

Rei*_*son 26

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

Arguments:

       d: a dissimilarity structure as produced by ‘dist’.
Run Code Online (Sandbox Code Playgroud)

更新

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

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

原版的

你想要的是什么

hclustfunc <- function(x, method = "complete", dmeth = "euclidean") {    
    hclust(dist(x, method = dmeth), method = method)
}
Run Code Online (Sandbox Code Playgroud)

然后

fit <- hclustfunc(mydata)
Run Code Online (Sandbox Code Playgroud)

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