How to extract counts as a vector from a table in R?

99封情书 提交于 2019-11-30 20:55:01

It honestly could not be any simpler. If you cannot figure this out, you will have lots of other problems:

> 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
> 

And for completeness, two more ways to get the data:

> 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
> 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!