Search code examples
rvectorfrequency

Making vector from frequency values in a table in R


I have a vector of characters

helloWorld <- c("H", "e", "l", "l", "o", " ",
                "W", "o", "r", "l", "d", "!")

I make a table of character frequency from it

frequency = table(helloWorld)

which gives :

> frequency
helloWorld
  ! d e H l o r W 
1 1 1 1 1 3 2 1 1 

Now I want to make a vector whose value will be :

[1]  1 1 1 1 1 3 2 1 1

I mean I just want to make a vector v with the frequency values. How can I possibly do that?


Solution

  • You can strip all of the table's attributes with as.vector()

    as.vector(table(helloWorld))
    # [1] 1 1 1 1 1 3 2 1 1
    

    Alternatively (and about twice as fast), convert helloWorld to factor and use tabulate()

    tabulate(factor(helloWorld))
    # [1] 1 1 1 1 1 3 2 1 1