计算列表中特定字符组合的出现次数

时间:2013-04-01 10:06:50

标签: r count combinations

我的问题非常简单..但是我无法解决这个问题...... 我使用1000次迭代在R上对2000个基因运行变量选择方法,并且在每次迭代中我得到了基因的组合。我想计算每个基因组合在R中出现的次数。 例如,我有

# for iteration 1
genes[1] "a" "b" "c"
# for iteration 2
genes[2] "a" "b"
# for iteration 3
genes[3] "a" "c"
# for iteration 4
genes [4] "a" "b"

这会给我

"a" "b" "c"  1
"a" "b"      2
"a"  "c"     1

我列出了未列出的列表并获得了每个基因的编号,但我感兴趣的是组合。我试图创建一个表,但每个基因载体的长度不等。提前谢谢。

1 个答案:

答案 0 :(得分:1)

我可以立即想到的方法是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个人的所有组合(可以这么说),然后拿表。首先,我将分解代码并将它们分开编写以便理解。然后我会将它们组合在一起以获得一个单行。

# 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"

因此,对于列表中的每组基因,您可以通过将其包裹在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来获取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