2011-12-11 52 views
5

我試圖寫一個函數來提取該表的頻率:如何從R表中提取計數作爲向量?

0 1 2 3 4 5 6 7 
30 22 9 12 2 5 1 16 

所以我想c(30, 22, 9, 12, 2, 5, 1, 16)

該表每次運行該函數時都會更改,所以我需要一些可以自動從表中提取信息的函數,所以我沒有每次都寫一個c()函數。

回答

14

說實話,這不能簡單些。如果你不明白這一點,你將有很多其他問題

> set.seed(42)       ## be reproducible 
> X <- sample(1:5, 50, replace=TRUE) ## our data 
> table(X)        ## our table 
X 
1 2 3 4 5 
7 6 9 10 18 
> str(table(X))       ## look at structure of object 
'table' int [1:5(1d)] 7 6 9 10 18 
- attr(*, "dimnames")=List of 1 
    ..$ X: chr [1:5] "1" "2" "3" "4" ... 
> as.numeric(table(X))     ## and just convert to vector 
[1] 7 6 9 10 18 
> 

以及物品是否完整,兩個方式來獲得數據:

> unname(table(X))      ## jdropping names reduces to the vector 
[1] 7 6 9 10 18 
> table(X)[]       ## or simply access it 
[1] 7 6 9 10 18 
> 
+0

呀對不起進出口新的R.「 table'int [1(1d)] 1 - attr(*,「dimnames」)= 1列表1 .. $ T:chr「TRUE」這就是我得到的表格的結構。我不知道爲什麼。 – user1021000

+0

然後也許你運行'table()'的對象只有一個值。在你的結尾重新運行我的答案中的代碼,並嘗試解決問題。 –

+0

謝謝,我現在明白了。在這裏幫助我很多! – user1021000