[英]How to calculate how many times vector appears in a list? in R
I have a list of 10,000 vectors, and each vector might have different elements and different lengths. 我有10,000个向量的列表,每个向量可能具有不同的元素和不同的长度。 I would like to know how many unique vectors I have and how often each unique vector appears in the list.
我想知道我有多少个唯一向量,以及每个唯一向量在列表中出现的频率。
I guess the way to go is the function "unique", but I don't know how I could use it to also get the number of times each vector is repeated. 我猜想方法是“唯一”函数,但是我不知道如何使用它来获得每个向量重复的次数。
So what I would like to get is something like that: 所以我想得到的是这样的:
"a" "b" "c" d" 301 “ a”“ b”“ c” d“ 301
"a" 277 “ a” 277
"b" c" 49 “ b” c“ 49
being the letters, the contents of each unique vector, and the numbers, how often are repeated. 是字母,每个唯一向量的内容以及数字,重复的频率。
I would really appreciate any possible help on this. 我真的很感谢在此方面可能提供的帮助。
thank you very much in advance. 提前非常感谢您。
Tina. 蒂娜
Maybe you should look at table
: 也许您应该看一下
table
:
Some sample data: 一些样本数据:
myList <- list(A = c("A", "B"),
B = c("A", "B"),
C = c("B", "A"),
D = c("A", "B", "B", "C"),
E = c("A", "B", "B", "C"),
F = c("A", "C", "B", "B"))
Paste your vectors together and tabulate them. 将向量粘贴在一起并制成表格。
table(sapply(myList, paste, collapse = ","))
#
# A,B A,B,B,C A,C,B,B B,A
# 2 2 1 1
You don't specify whether order matters (that is, is A, B the same as B, A). 您无需指定顺序是否重要(即A,B与B,A相同)。 If it does, you can try something like:
如果是这样,您可以尝试如下操作:
table(sapply(myList, function(x) paste(sort(x), collapse = ",")))
#
# A,B A,B,B,C
# 3 3
Wrap this in data.frame
for a vertical output instead of horizontal, which might be easier to read. 将其包装在
data.frame
以获得垂直输出而不是水平输出,这可能更易于阅读。
Also, do be sure to read How to make a great R reproducible example? 另外,请务必阅读如何制作出色的R可重现示例? as already suggested to you.
正如已经向您建议的。
As it is, I'm just guessing at what you're trying to do. 实际上,我只是在猜测您要做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.