学员交流群有提问,说他虽然会绘制韦恩图了,但是想提取图中指定的元素,自己弄的代码非常笨拙,感觉是R语言学的不够好,希望我可以秀一秀高阶代码。恰好今天没有什么可以分享的,就写这个教程吧!
set.seed(123456789)
g1=LETTERS[sample(1:26,15)]
g2=LETTERS[sample(1:26,15)]
g3=LETTERS[sample(1:26,15)]
g4=LETTERS[sample(1:26,15)]
VENN.LIST=list(g1=g1,
g2=g2,
g3=g3,
g4=g4)
VENN.LIST
一般来说,这4个向量里面的元素大概率是有交集的:
> VENN.LIST
$g1
[1] "T" "B" "G" "P" "K" "L" "M" "X" "U" "I" "R" "J" "O" "E" "S"
$g2
[1] "F" "J" "O" "L" "Z" "D" "M" "N" "I" "T" "P" "B" "E" "C" "U"
$g3
[1] "G" "M" "U" "F" "Y" "I" "W" "Q" "H" "J" "T" "A" "X" "E" "C"
$g4
[1] "P" "M" "O" "N" "S" "Y" "Q" "K" "U" "W" "T" "G" "C" "F" "H"
代码随处可以搜索到:
require("VennDiagram")
venn.plot <- venn.diagram(VENN.LIST , NULL,
fill=c("red", "blue",'green','black'),
alpha=c(0.5,0.5,0.5,0.5), cex = 2, cat.fontface=4,
category.names= names(VENN.LIST),
main="venn.diagram")
grid.draw(venn.plot)
出图如下所示:
代码如下:
x=VENN.LIST
names(x)
id=unique(unlist(x))
id
y=do.call(cbind,lapply(x, function(i){
sign( id %in% i)
}))
rownames(y)=id
y=data.frame(y)
y$sum=rowSums(y)
y=y[order(y$sum,decreasing = T),]
head(y)
会得到如下所示的表格:
> head(y)
g1 g2 g3 g4 sum
T 1 1 1 1 4
M 1 1 1 1 4
U 1 1 1 1 4
G 1 0 1 1 3
P 1 1 0 1 3
I 1 1 1 0 3
可以看到,出现4次的元素是 T,M,U 这3个,跟前面的韦恩图是对应的。
这个时候,如果你的合作者并不擅长代码,可以直接打开这个csv文件,根据sum列进行筛选即可。
z=apply(y,1,function(x){paste(x[1:4],collapse = '-')})
as.data.frame(sort(table(z)))
如下所示:
> as.data.frame(sort(table(z)))
z Freq
1 0-0-1-0 1
2 0-1-0-1 1
3 1-0-0-0 1
4 1-0-1-0 1
5 1-0-1-1 1
6 0-1-0-0 2
7 0-1-1-1 2
8 1-0-0-1 2
9 1-1-0-0 2
10 1-1-0-1 2
11 1-1-1-0 3
12 1-1-1-1 3
13 0-0-1-1 4
> which(z=='1-1-1-1')
T M U
1 2 3
前面的4个随机的向量的交集可以有13种情况,各个情况的元素的数量都展现出来了,提取需要的组合,很简单的which函数即可:
代码如下:
library(UpSetR)
p=upset(fromList(VENN.LIST), order.by = "freq")
p
p$New_data
它得到 p$New_data 其实就是我们自己制作的 y
归根结底都是R基础知识的掌握而已。