简体   繁体   中英

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. 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" 277

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

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). 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.


Also, do be sure to read How to make a great R reproducible example? as already suggested to you.

As it is, I'm just guessing at what you're trying to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM