R:分类变量的同频表-热图/几何图
您好,我想创建热图,显示几个变量的同频 让我们看一些代码:R:分类变量的同频表-热图/几何图,r,ggplot2,heatmap,categorical-data,R,Ggplot2,Heatmap,Categorical Data,您好,我想创建热图,显示几个变量的同频 让我们看一些代码: a <- c(1,1,1,1) b <-c(1,1,1,0) c<- c(1,1,0,0) d <- c(1,0,0,0) df <- cbind(a,b,c,d) df a b c d [1,] 1 1 1 1 [2,] 1 1 1 0 [3,] 1 1 0 0 [4,] 1 0 0 0 a应该有一个函数直接执行此操作,但是,这里有一个使用outer的基本R方法。我们写了一个计算比率的函数
a <- c(1,1,1,1)
b <-c(1,1,1,0)
c<- c(1,1,0,0)
d <- c(1,0,0,0)
df <- cbind(a,b,c,d)
df
a b c d
[1,] 1 1 1 1
[2,] 1 1 1 0
[3,] 1 1 0 0
[4,] 1 0 0 0
a应该有一个函数直接执行此操作,但是,这里有一个使用outer
的基本R方法。我们写了一个计算比率的函数
calc_freq <- function(x, y) {
mean(df[, x] == df[, y] & df[, x] == 1 & df[, y] == 1)
}
如果您需要行和列名,我们可以使用dimnames
dimnames(mat) <- list(colnames(df), colnames(df))
有趣的功能,以及如何可视化外部使用例如ggplot2 geomłu tile的结果?@Mikołaj我认为,为此,您需要重塑数据。类似于mat%>%as_tible()%%>%gather%>%ggplot()+aes(键,值)+geom_tile()
hi,@RonakShah,如果可能的话,你能解释一下这个函数吗?因为我不明白…@Paololorenzin嗨..你不明白代码的哪一部分?@Paololorenzin是的,没错。因此,在outer
中,我们生成所有可能的列名组合,在函数中,我们借助这些列名对数据进行子集划分,并计算其具有相等1值的比率。
mat <- outer(colnames(df), colnames(df), Vectorize(calc_freq))
mat
# [,1] [,2] [,3] [,4]
#[1,] 1.00 0.75 0.50 0.25
#[2,] 0.75 0.75 0.50 0.25
#[3,] 0.50 0.50 0.50 0.25
#[4,] 0.25 0.25 0.25 0.25
dimnames(mat) <- list(colnames(df), colnames(df))
library(tidyverse)
data.frame(mat) %>%
rownames_to_column() %>%
gather(key, value, -rowname) %>%
ggplot() + aes(rowname, key, fill = value) +
geom_tile()