Jake Fisher
Jake Fisher

Reputation: 3310

How do I count the number of unique vectors in a list?

Say I have a list of vectors. I want a list of the unique vectors in that list, and their frequencies. I can get a list of the unique values with unique, but I can't figure out how to get a vector of the counts.

my.list <- list(c(1, 1, 0), c(1, 1, 0))
> unique(my.list)  # gives correct answer
# [[1]]
# [1] 1 1 0

Now I want something that gives me a vector of the number of times each element of unique(my.list) was repeated. In this case, that should be a vector with the element 2.

Using table doesn't work, because it takes each of the elements of the vector (the 0 and 1 values) separately:

> table(my.list)
#          my.list.2
# my.list.1 0 1
#         0 1 0
#         1 0 2

Any ideas? I would rather not paste these into a string and then re-separate them into vectors if I can help it.

Upvotes: 7

Views: 545

Answers (2)

alistaire
alistaire

Reputation: 43354

One approach, maybe more complicated than it needs to be:

library(dplyr)
df <- do.call(rbind, my.list) %>% as.data.frame()
df %>% group_by_(.dots = names(df)) %>% summarise(count = n())

# Source: local data frame [1 x 4]
# Groups: V1, V2 [?]
# 
#      V1    V2    V3 count
#   (dbl) (dbl) (dbl) (int)
# 1     1     1     0     2

Edit:

Per the comment below by @docendodiscimus, group_by and summarise(n()) is equivalent to count_:

df %>% count_(names(df))    # or just count_(df, names(df))

# Source: local data frame [1 x 4]
# Groups: V1, V2 [?]
# 
#      V1    V2    V3     n
#   (dbl) (dbl) (dbl) (int)
# 1     1     1     0     2

Upvotes: 4

thelatemail
thelatemail

Reputation: 93938

Use match on the entire list vs. the unique list:

my.list <- list(c(1, 1, 0), c(1, 1, 0), c(2, 1, 0))
table(match(my.list,unique(my.list)))

#1 2 
#2 1

cbind(
  data.frame(id=I(unique(my.list))),  
  count=as.vector(table(match(my.list,unique(my.list)))) 
)
#       id count
#1 1, 1, 0     2
#2 2, 1, 0     1

Upvotes: 8

Related Questions