Lucia
Lucia

Reputation: 647

find out word frequency in a table according to a list

Now I have a dtm, so I turn the dtm as a frequency table

freqs <- as.data.frame(inspect(dtm1))

Here's how freqs looks like, it contains one row shows the frequency of these words in a document

I    really   hate   school   how   can  are  you  hi
4      5        3       2      3     1    4    5   1

I have a list

list <- c("hi", "how", "are", "you")

How can I find out the frequency of words in the frequency table according to the list, then compile these word frequencies in a table

hi  how  are  you
1    3    4   5

Upvotes: 0

Views: 80

Answers (2)

Abdou
Abdou

Reputation: 13274

You can do this in two ways:

Using table():

words <- "hi how are you doing today I really hate school and I want to quit how can you still go to school"
lst <- c("hi", "how", "are", "you")
table(strsplit(words, split=" "))[lst]
hi how are you 
1   2   1   2 

Working with data.frame():

df <- as.data.frame(table(strsplit(words,split=" ")))
colnames(df) <- c("words","freqs")
df[df$words%in%lst,]
   words freqs
2    are     1
7     hi     1
8    how     2
17   you     2

Upvotes: 0

Conta
Conta

Reputation: 585

If the words are the variable names in the data.frame

> freqs[,list]
  hi how are you
1  1   3   4   5

Upvotes: 1

Related Questions