在R/ggplot2中生成层次聚类碎石图报错求助
解决层次聚类碎石图的代码错误
错误原因
tibble 3.0.0+ 不再允许直接将数值向量传入as.tibble(),必须明确将向量转换为单列数据框,否则会触发argument ".data" is missing的错误。你的代码中myhclust$height是一个数值向量,直接用as.tibble()处理不符合新版本tibble的要求。
可行解决方案
方案1:直接用tibble()构造数据框(推荐)
这种写法更直观,避免向量转数据框的兼容性问题:
# 先加载必要的包 library(tidyverse) # 构造碎石图所需的数据 scree_df <- tibble( height = myhclust$height, groups = length(myhclust$height):1 ) # 绘制碎石图 ggplot(scree_df, aes(x = groups, y = height)) + geom_point() + geom_line()
方案2:用as_tibble_col()适配向量转数据框
如果偏好管道写法,可以用tibble包的as_tibble_col()函数明确将向量转为单列数据框:
library(tidyverse) myhclust$height %>% as_tibble_col(column_name = "height") %>% mutate(groups = length(myhclust$height):1) %>% ggplot(aes(x = groups, y = height)) + geom_point() + geom_line()
注意事项
- 确保已安装并加载
tidyverse(或单独的ggplot2、dplyr、tibble包) myhclust必须是合法的hclust对象,可通过class(myhclust)确认类型
内容的提问来源于stack exchange,提问作者laurent-bourbaki
相关产品推荐
相关产品推荐

