如何从R中的表中提取计数作为向量? [英] How to extract counts as a vector from a table in R?
本文介绍了如何从R中的表中提取计数作为向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个函数来提取此表的频率:
I'm trying to write a function to extract the frequencies of this table:
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()函数.
The table changes each time I run the function, so I need something that can extract the information from the table automatically, so I don't have write a c() function each time.
推荐答案
让我们从table()
创建一个结果对象并对其进行检查:
Let's create a results object from table()
and examine it:
> 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.integer(table(X)) ## and just convert to vector
[1] 7 6 9 10 18
> as.numeric(table(X)) ## or use `numeric()`
[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
>
这篇关于如何从R中的表中提取计数作为向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文