同类热图(实际值而非相关系数)

问题描述 投票:0回答:1

在 R 中,我被困在如何创建下面的数据表和图表上。 我想要这组数据

person_id 状况
1 哮喘
1 心脏疾病
1 癌症
2 癌症
3 湿疹
3 背痛
3 癌症
4 哮喘
4 背痛
4 湿疹
4 高血压
4 糖尿病
4 心脏疾病
5 心脏疾病
6 哮喘
6 背痛
7 心脏疾病
10 哮喘

并整理它,使其看起来像这样

我刚刚针对三种医疗状况做了这件事。

然后我想创建一个热图来直观地说明数据。沿着这些思路。

如有任何帮助,我们将不胜感激。谢谢!

r ggplot2 matrix correlation
1个回答
0
投票

要获得显示诊断一起发生的频率的热图,您可以首先通过

left_join
person_id
获取数据本身,然后使用
count
获取计数。最后,您可以使用
geom_tile
创建热图。

注意:我放弃了对角线。

library(dplyr, warn = FALSE)
library(ggplot2)

dat |>
  left_join(dat,
    by = "person_id", 
    relationship = "many-to-many",
    suffix = c("1", "2")
  ) |>
  # Drop diagonal elements
  filter(
    Condition1 != Condition2, .by = person_id
  ) |>
  count(Condition1, Condition2) |> 
  ggplot(aes(Condition1, Condition2, fill = n)) +
  geom_tile()

数据

dat <- data.frame(
  stringsAsFactors = FALSE,
  person_id = c(
    1L, 1L, 1L, 2L, 3L, 3L, 3L, 4L,
    4L, 4L, 4L, 4L, 4L, 5L, 6L, 6L, 7L, 10L
  ),
  Condition = c(
    "asthma", "heart_disease",
    "cancer", "cancer", "eczema", "back_pain", "cancer", "asthma",
    "back_pain", "eczema", "hypertension", "diabetes",
    "heart_disease", "heart_disease", "asthma", "back_pain",
    "heart_disease", "asthma"
  )
)
© www.soinside.com 2019 - 2024. All rights reserved.