9

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

So I want to get c(30, 22, 9, 12, 2, 5, 1, 16).

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user1021000
  • 237
  • 1
  • 3
  • 8

1 Answers1

16

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
> 
Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • Good answer. And use `as.numeric(names(table(data$variable)))` to catch the unique values. – Marco Oct 08 '21 at 10:44
  • Just to note that if you have an ordered variable as the basis for the table, as.numeric() will remove the ordering information. That may be a reason to choose (or not) that option. – Elin Jun 17 '23 at 16:14