我试着通过以下方式构建聚类方法:
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
什么是正确的方法呢?
请阅读您使用的功能的帮助.?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
和聚类方法.