2014-11-06 55 views
2

我有2個載體:填補了一個表中的R

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 

現在我想c2有以下形式:

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

我怎樣才能擺脫這些表的載體(2,3,2,2,1,1,1)和(2,2,2,0,0,1,0)?

+0

也[**這**](http://stackoverflow.com/questions/19773435/how-can-見你的力量包含在一個表中的水平/ 19773510#19773510)或[**這**](http://stackoverflow.com/questions/1617061/including-absent - 值功能於表成果在-R/1617150#1617150)。 – Henrik 2014-11-06 14:48:22

回答

4

所以R不知道有缺失的值。說服它的最簡單方法是指定factorlevels包含缺失的元素。

例如

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

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

對於這個問題的第二部分,通常表本身足以滿足大多數目的。

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

如果您忽略「0」標頭,那麼您幾乎可以進行任何矢量操作。但是,如果你想徹底刪除標題,您可以轉換成原始數字陣列

> as.numeric(a) 
[1] 2 2 2 0 0 1 0 
+0

我認爲OP需要對應於'c1'的級別,而不是手動設置它們 – 2014-11-06 14:23:02

2

使用factor,爲了設定與c1

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

或者使用union(如@Svens刪除答覆中提到)

table(factor(c2, levels = sort(union(c1, c2)))) 
# 0 1 2 3 4 5 6 
# 2 2 2 0 0 1 0 
空項合格 c1唯一值的 c2 levels

爲了得到實際使用價值,請使用as.numeric

as.numeric(table(factor(c2, levels = sort(unique(c1))))) 
## [1] 2 2 2 0 0 1 0