如何在R中计算范围型身高与寿命列的相关性并可视化?
处理范围格式数据并计算身高与寿命的相关性及可视化
1. 数据预处理:将范围值转换为数值均值
你的Height..in.和Longevity..yrs.列是范围格式(比如"12-15"),无法直接用cor()计算。首先需要把这些范围转成可计算的数值,最常用的方式是取范围的平均值:
# 加载必要包 library(tidyverse) # 假设你的数据集名为dog_breeds,先处理身高列 dog_breeds <- dog_breeds %>% # 拆分身高范围为上下限并转成数值 separate(Height..in., into = c("height_low", "height_high"), sep = "-", convert = TRUE) %>% # 计算身高均值 mutate(height_mean = (height_low + height_high)/2) %>% # 处理寿命列 separate(Longevity..yrs., into = c("longevity_low", "longevity_high"), sep = "-", convert = TRUE) %>% mutate(longevity_mean = (longevity_low + longevity_high)/2) %>% # 移除临时辅助列(可选) select(-c(height_low, height_high, longevity_low, longevity_high))
如果数据里存在单值格式的异常值(比如"10"这种没有范围的),可以先做清洗:
# 把单值转换为自身范围,保证拆分逻辑统一 dog_breeds <- dog_breeds %>% mutate( Height..in. = ifelse(!str_detect(Height..in., "-"), paste0(Height..in., "-", Height..in.), Height..in.), Longevity..yrs. = ifelse(!str_detect(Longevity..yrs., "-"), paste0(Longevity..yrs., "-", Longevity..yrs.), Longevity..yrs.) )
2. 计算相关性
预处理完成后,就可以用cor()函数计算皮尔逊相关系数,记得处理缺失值:
# 计算身高均值与寿命均值的相关性,忽略缺失值 correlation <- cor(dog_breeds$height_mean, dog_breeds$longevity_mean, use = "complete.obs") cat("身高与寿命的相关系数:", correlation, "\n")
如果小型犬寿命更长的结论成立,你会得到一个负相关系数(身高越低,寿命越长)。
3. 带犬种名称的可视化
用ggplot2绘制散点图,并借助ggrepel包避免犬种标签重叠:
# 若未安装ggrepel,先运行install.packages("ggrepel") library(ggrepel) # 绘制带标签的相关性散点图 ggplot(dog_breeds, aes(x = height_mean, y = longevity_mean)) + geom_point(color = "#2c3e50", size = 2) + # 自动调整标签位置避免重叠 geom_text_repel(aes(label = Breed), size = 3, color = "#e74c3c") + # 添加线性趋势线 geom_smooth(method = "lm", se = FALSE, color = "#3498db") + # 设置图表标题与坐标轴标签 labs( x = "平均身高(英寸)", y = "平均寿命(年)", title = "犬种身高与寿命的相关性", subtitle = paste("相关系数:", round(correlation, 2)) ) + theme_minimal()
内容的提问来源于stack exchange,提问作者Shashivydyula
相关产品推荐
相关产品推荐

