hearse
hearse

Reputation: 389

Finding how many times the words in one array occur in another array in R?

Hi i have two arrays 'topWords' of length N (unique words), and 'observedWords' with length < N (repetitions of words).

I'd like an array of counts 'countArray' of length N containing the number of times each of the N words in 'topWords' occurs in the array 'observedWords'. What is an efficient way to do this in R?

Upvotes: 0

Views: 97

Answers (3)

Tyler Rinker
Tyler Rinker

Reputation: 110062

Using RScriv's example:

topWords <- paste(LETTERS, letters, sep = "")
observedWords <- c("Bb", rep("Mm", 2), rep("Pp", 3))

library(qdap)
termco(observedWords, match.list=topWords)

##   all word.count Aa        Bb Cc Dd Ee Ff Gg Hh Ii Jj Kk Ll        Mm Nn Oo        Pp Qq Rr Ss Tt Uu Vv Ww Xx Yy Zz
## 1 all          6  0 1(16.67%)  0  0  0  0  0  0  0  0  0  0 2(33.33%)  0  0 3(50.00%)  0  0  0  0  0  0  0  0  0  0

And if you want just the frequencies wrap with the counts method:

counts(termco(observedWords, match.list=topWords))

Upvotes: 1

Rich Scriven
Rich Scriven

Reputation: 99391

Here's a simple example using match and unique. Then ifelse at the end to turn the NA values into 0.

> topWords <- paste(LETTERS, letters, sep = "")
> topWords
##  [1] "Aa" "Bb" "Cc" "Dd" "Ee" "Ff" "Gg" "Hh" "Ii" "Jj" "Kk" "Ll" "Mm" "Nn" "Oo"
## [16] "Pp" "Qq" "Rr" "Ss" "Tt" "Uu" "Vv" "Ww" "Xx" "Yy" "Zz"
> observedWords <- c("Bb", rep("Mm", 2), rep("Pp", 3))
> observedWords
## [1] "Bb" "Mm" "Mm" "Pp" "Pp" "Pp"
> mm <- match(topWords, unique(observedWords))
> ifelse(is.na(mm), 0, mm)
## [1] 0 1 0 0 0 0 0 0 0 0 0 0 2 0 0 3 0 0 0 0 0 0 0 0 0 0

Upvotes: 1

Bangyou
Bangyou

Reputation: 9816

You could use table and match functions. See example codes below. Not sure whether they are suitable for you.

topWords <- c('A', 'B', 'C')
observedWords <- c(rep('A', 5), rep('B', 4))
count <- table(observedWords)
pos <- match(topWords, names(count))
fre <- as.numeric(count)[pos]

Upvotes: 1

Related Questions