[英]How to use 'hclust' as function call in R
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
What's the right way to do it? 什么是正确的方法呢?
Do read the help for functions you use. 请阅读您使用的功能的帮助。 ?hclust
is pretty clear that the first argument d
is a dissimilarity object, not a matrix: ?hclust
很清楚,第一个参数d
是一个相异对象,而不是一个矩阵:
Arguments:
d: a dissimilarity structure as produced by ‘dist’.
As the OP has now updated their question, what is need is 由于OP现在已经更新了他们的问题,所需要的是
hclustfunc <- function(x) hclust(x, method="complete")
distfunc <- function(x) as.dist((1-cor(t(x)))/2)
d <- distfunc(mydata)
fit <- hclustfunc(d)
What you want is 你想要的是什么
hclustfunc <- function(x, method = "complete", dmeth = "euclidean") {
hclust(dist(x, method = dmeth), method = method)
}
and then 然后
fit <- hclustfunc(mydata)
works as expected. 按预期工作。 Note you can now pass in the dissimilarity coefficient method as dmeth
and the clustering method. 请注意,您现在可以将相异系数方法作为dmeth
和聚类方法传递。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.