我能立即想到的方法是给paste他们,然后使用table如下:
genes_p <- sapply(my_genes, paste, collapse=";")
freq <- as.data.frame(table(genes_p))
#    Var1 Freq
# 1   a;b    2
# 2 a;b;c    1
# 3     c    1
上述解决方案假定基因按名称排序,并且相同的基因 id 在列表的元素中不会出现多次。如果你想同时考虑两者,那么:
# sort genes before pasting
genes_p <- sapply(my_genes, function(x) paste(sort(x), collapse=";"))
# sort + unique
genes_p <- sapply(my_genes, function(x) paste(sort(unique(x)), collapse=";"))
编辑:根据 OP 在评论中的问题,我们的想法是尽可能获得 2'ers 的所有组合(可以这么说),然后上桌。首先,我将分解代码并将它们分开编写以便理解。然后我将它们组合在一起得到一个单线。
# you first want all possible combinations of length 2 here
# that is, if vector is:
v <- c("a", "b", "c")
combn(v, 2)
#      [,1] [,2] [,3]
# [1,] "a"  "a"  "b" 
# [2,] "b"  "c"  "c" 
这给出了一次取 2 个的所有组合。现在,您可以类似地粘贴它。combn还允许函数参数。
combn(v, 2, function(y) paste(y, collapse=";"))
# [1] "a;b" "a;c" "b;c"
因此,对于列表中的每组基因,您可以通过将其包裹在 a 周围来执行相同的操作sapply,如下所示:
sapply(my_genes, function(x) combn(x, min(length(x), 2), function(y) 
                                      paste(y, collapse=";")))
这min(length(x), 2)是必需的,因为您的某些基因列表可能只有 1 个基因。
# [[1]]
# [1] "a;b" "a;c" "b;c"
# [[2]]
# [1] "a;b"
# [[3]]
# [1] "c"
# [[4]]
# [1] "a;b"
现在,您可以使用unlist它来获取 a vector,然后使用它table来获取频率:
table(unlist(sapply(l, function(x) combn(x, min(length(x), 2), function(y) 
                                           paste(y, collapse=";")))))
# a;b a;c b;c   c 
#   3   1   1   1 
您可以依次包装它as.data.frame(.)以获得data.frame:
as.data.frame(table(unlist(sapply(l, function(x) combn(x, min(length(x), 2), 
                     function(y) paste(y, collapse=";"))))))
#   Var1 Freq
# 1  a;b    3
# 2  a;c    1
# 3  b;c    1
# 4    c    1