How to create a table for the number of unique values in list of vectors in R?


To create a table for the number of unique values in list of vectors, we can use mtabulate function of qdapTools package. For example, if we have a list of vectors say LIST that contains some vectors then the table for the number of unique values in the vectors of LIST can be found by using mtabulate(LIST).

Example

Consider the below list −

 Live Demo

x1<-rpois(5,2)
x2<-rpois(5,5)
x3<-rpois(5,2)
x4<-rpois(10,5)
x5<-rpois(20,5)
List1<-list(x1,x2,x3,x4,x5)
List1

Output

[[1]]
[1] 2 1 1 1 3
[[2]]
[1] 5 4 4 2 5
[[3]]
[1] 2 1 1 4 1
[[4]]
[1] 4 5 7 3 6 7 1 5 4 1
[[5]]
[1] 4 3 6 6 6 2 3 9 8 4 4 4 11 3 7 7 5 11 4 6

Loading qdapTools package and finding the table of number of unique values in the vectors of List1 −

Example

library(qdapTools)
mtabulate(List1)

Output

  1  2  3  4  5  6  7  8  9  11
1 3  1  1  0  0  0  0  0  0  0
2 0  1  0  2  2  0  0  0  0  0
3 3  1  0  1  0  0  0  0  0  0
4 2  0  1  2  2  1  2  0  0  0
5 0  1  3  5  1  4  2  1  1  2

Example

 Live Demo

y1<-rpois(20,2)
y2<-rpois(20,2)
y3<-rpois(20,5)
y4<-rpois(20,1)
y5<-rpois(20,2)
y6<-rpois(20,5)
y7<-rpois(20,2)
y8<-rpois(20,4)
List2<-list(y1,y2,y3,y4,y5,y6,y7,y8)
List2

Output

[[1]]
[1] 1 4 1 3 3 4 2 1 6 2 4 4 2 1 0 3 1 2 4 1
[[2]]
[1] 3 3 3 1 0 0 4 1 2 6 2 3 2 2 2 5 1 5 2 1
[[3]]
[1] 7 4 6 4 3 3 7 1 3 9 3 8 3 6 8 3 3 4 4 7
[[4]]
[1] 0 0 1 1 1 1 4 4 1 0 1 1 0 2 0 0 0 4 1 1
[[5]]
[1] 1 2 2 2 0 1 3 0 3 1 0 0 3 4 4 0 1 2 1 3
[[6]]
[1] 4 5 6 5 3 6 6 3 5 5 5 7 5 3 6 2 5 7 4 7
[[7]]
[1] 0 1 3 2 2 1 1 4 3 0 2 2 2 5 0 2 2 0 1 2
[[8]]
[1] 4 3 3 4 4 6 4 8 4 6 5 2 4 3 4 4 3 0 7 1

Finding the table of number of unique values in the vectors of List2 −

Example

mtabulate(List2)

Output

   0  1  2  3  4  5  6  7  8  9
1  1  6  4  3  5  0  1  0  0  0
2  2  4  6  4  1  2  1  0  0  0
3  0  1  0  7  4  0  2  3  2  1
4  7  9  1  0  3  0  0  0  0  0
5  5  5  4  4  2  0  0  0  0  0
6  0  0  1  3  2  7  4  3  0  0
7  4  4  8  2  1  1  0  0  0  0
8  1  1  1  4  8  1  2  1  1  0

Updated on: 16-Mar-2021

129 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements