如何在R中使用“ hclust”作为函数调用 [英] How to use 'hclust' as function call in R
本文介绍了如何在R中使用“ hclust”作为函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试通过以下方式将聚类方法构造为函数:
I tried to construct the clustering method as function the following ways:
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)
但是为什么会出现以下错误:
But why it gives the following error:
Error in if (is.na(n) || n > 65536L) stop("size cannot be NA nor exceed 65536") :
missing value where TRUE/FALSE needed
什么是正确的方法?
推荐答案
请阅读所用功能的帮助。 ?hclust
很清楚,第一个参数 d
是一个不相似的对象,而不是矩阵:
Do read the help for functions you use. ?hclust
is pretty clear that the first argument d
is a dissimilarity object, not a matrix:
Arguments:
d: a dissimilarity structure as produced by ‘dist’.
更新
因为OP已经存在更新了他们的问题,需要的是
Update
As the OP has now updated their question, what is need is
hclustfunc <- function(x) hclust(x, method="complete")
distfunc <- function(x) as.dist((1-cor(t(x)))/2)
d <- distfunc(mydata)
fit <- hclustfunc(d)
原始
您想要的是
Original
What you want is
hclustfunc <- function(x, method = "complete", dmeth = "euclidean") {
hclust(dist(x, method = dmeth), method = method)
}
然后
fit <- hclustfunc(mydata)
可以正常工作。请注意,您现在可以将差异系数方法作为 dmeth
和聚类方法进行传递。
works as expected. Note you can now pass in the dissimilarity coefficient method as dmeth
and the clustering method.
这篇关于如何在R中使用“ hclust”作为函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文