2

I've got 2 vectors:

c1 <- c(1,2,0,1,3,4,5,6,1,2,3,0)
c2 <- c(1,2,0,5,0,2,1)

> table(c1)   
c1   
0 1 2 3 4 5 6   
2 3 2 2 1 1 1   
> table(c2)  
c2  
0 1 2 5   
2 2 2 1  

Now I want c2 to have the following form:

> table(c2)  
c2  
0 1 2 3 4 5 6   
2 2 2 0 0 1 0

How can I get out of these tables the vectors (2, 3, 2, 2, 1, 1, 1) and (2, 2, 2, 0, 0, 1, 0)?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Anita
  • 759
  • 1
  • 10
  • 23
  • See also [**this**](http://stackoverflow.com/questions/19773435/how-can-you-force-inclusion-of-a-level-in-a-table-in-r/19773510#19773510) or [**this**](http://stackoverflow.com/questions/1617061/including-absent-values-in-table-results-in-r/1617150#1617150). – Henrik Nov 06 '14 at 14:48

2 Answers2

4

So R doesn't know that there are missing values. The easiest way to convince it of this is to specify that the levels of the factor include missing elements.

For example

> table(factor(c2, levels=0:6))

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

For the second part of this question, usually the table itself is adequate for most purposes.

> a <- table(factor(c2, levels=0:6))
> a[1] + 1
0
3

if you ignore the "0" header, then you can do almost any vector manipulation. But if you want to remove the headers completely, you can convert to a raw numeric array

> as.numeric(a)
[1] 2 2 2 0 0 1 0
user295691
  • 7,108
  • 1
  • 26
  • 35
2

Use factor and pass unique values of c1 to levels of c2 in order to set empty entries corresponding to c1 values

table(factor(c2, levels = sort(unique(c1))))
# 0 1 2 3 4 5 6 
# 2 2 2 0 0 1 0 

Or use union (as mentioned in @Svens deleted answer)

table(factor(c2, levels = sort(union(c1, c2))))
# 0 1 2 3 4 5 6 
# 2 2 2 0 0 1 0 

In order to get the actual values use as.numeric

as.numeric(table(factor(c2, levels = sort(unique(c1)))))
## [1] 2 2 2 0 0 1 0
David Arenburg
  • 91,361
  • 17
  • 137
  • 196