0

Let's say I have two vectors

x <- c(1, 2, 2, 3, 4, 4, 5, 5, 5) 
y <- c(3, 3, 3, 4, 5, 6, 6, 7, 7)

The unique numbers among all the numbers in these vectors are 1:7. I know that if I use the table function in R, I can count the number of unique entries in each of the vectors. For example, if I apply the table function to the first vector, I will get

table(x)
#x
# 1 2 3 4 5 
# 1 2 1 2 3 

Applying it to the second vector, I will get

table(y)
# y
# 3 4 5 6 7 
# 3 1 1 2 2 

How can I get it to count the number of occurrences of all unique entries in both vectors? For example, I'd like to produce the following results:

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

for the first vector and

1 2 3 4 5 6 7
0 0 3 1 1 2 2
MrFlick
  • 195,160
  • 17
  • 277
  • 295
Vivek Subramanian
  • 1,174
  • 2
  • 17
  • 31

2 Answers2

2

First, generate a list of the values you want to get counts for in both vectors

lvl<-unique(c(x,y))

Then explicitly list those values as levels of a factor before doing table

table(factor(x, lvl))
table(factor(y, lvl))
MrFlick
  • 195,160
  • 17
  • 277
  • 295
0

table(factor(x, unique(union(x,y))))

table(factor(y, unique(union(x,y))))

NRLP
  • 568
  • 3
  • 16