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

 手机用户2602905817_973 发布于 2023-02-13 12:13

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

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和聚类方法.

    2023-02-13 12:16 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有