Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting Strings and Generating Frequency Tables in R

I have a column of firm names in an R dataframe that goes something like this:

"ABC Industries"  
"ABC Enterprises"  
"123 and 456 Corporation"  
"XYZ Company"

And so on. I'm trying to generate frequency tables of every word that appears in this column, so for example, something like this:

Industries   10  
Corporation  31  
Enterprise   40  
ABC          30  
XYZ          40  

I'm relatively new to R, so I was wondering of a good way to approach this. Should I be splitting the strings and placing every distinct word into a new column? Is there a way to split up a multi-word row into multiple rows with one word?

like image 338
aesir Avatar asked Dec 05 '22 18:12

aesir


2 Answers

If you wanted to, you could do it in a one-liner:

R> text <- c("ABC Industries", "ABC Enterprises", 
+            "123 and 456 Corporation", "XYZ Company")
R> table(do.call(c, lapply(text, function(x) unlist(strsplit(x, " ")))))

        123         456         ABC         and     Company 
          1           1           2           1           1 
Corporation Enterprises  Industries         XYZ 
          1           1           1           1 
R> 

Here I use strsplit() to break each entry intro components; this returns a list (within a list). I use do.call() so simply concatenate all result lists into one vector, which table() summarises.

like image 87
Dirk Eddelbuettel Avatar answered Dec 07 '22 07:12

Dirk Eddelbuettel


Here is another one-liner. It uses paste() to combine all of the column entries into a single long text string, which it then splits apart and tabulates:

text <- c("ABC Industries", "ABC Enterprises", 
         "123 and 456 Corporation", "XYZ Company")

table(strsplit(paste(text, collapse=" "), " "))
like image 25
Josh O'Brien Avatar answered Dec 07 '22 08:12

Josh O'Brien