Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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.

like image 609
Jake Fisher Avatar asked Mar 16 '16 21:03

Jake Fisher


People also ask

How do you count unique values in a list?

You can use the combination of the SUM and COUNTIF functions to count unique values in Excel. The syntax for this combined formula is = SUM(IF(1/COUNTIF(data, data)=1,1,0)). Here the COUNTIF formula counts the number of times each value in the range appears. The resulting array looks like {1;2;1;1;1;1}.

How do you count unique values in a vector?

The length of values vector gives you the number of unique values. Show activity on this post. uniqueN function from data. table is equivalent to length(unique(group)) .

How do you find the number of unique values in a vector in R?

To find unique values in a column in a data frame, use the unique() function in R. In Exploratory Data Analysis, the unique() function is crucial since it detects and eliminates duplicate values in the data.


1 Answers

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
like image 137
thelatemail Avatar answered Oct 13 '22 11:10

thelatemail