Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use bigrams and trigrams using tidy text

Tags:

r

token

tidytext

I'm trying to use both a bigram and a trigram using tidytext. What code could I use for the token to look for 2 and 3 words.

This is the code for using bigrams only:

library(tidytext)
library(janeaustenr)

austen_bigrams <- austen_books() %>%
  unnest_tokens(bigram, text, token = "ngrams", n = 2)

austen_bigrams
like image 393
Claudia Avatar asked Aug 13 '17 18:08

Claudia


1 Answers

If you look at ?unnest_tokens, it tells you ... is for parameters passed to the tokenizer. For ngrams, that's tokenizers::tokenize_ngrams, and if you look at its help page, it has an n_min parameter, so you can do

library(magrittr)
library(tidytext)
library(janeaustenr)

austen_bigrams <- austen_books() %>% 
    head(1000) %>%    # otherwise this will get very large
    unnest_tokens(bigram, text, token = "ngrams", n = 3, n_min = 2)

austen_bigrams
#> # A tibble: 19,801 x 2
#>                   book                bigram
#>                 <fctr>                 <chr>
#>  1 Sense & Sensibility             sense and
#>  2 Sense & Sensibility sense and sensibility
#>  3 Sense & Sensibility       and sensibility
#>  4 Sense & Sensibility    and sensibility by
#>  5 Sense & Sensibility        sensibility by
#>  6 Sense & Sensibility   sensibility by jane
#>  7 Sense & Sensibility               by jane
#>  8 Sense & Sensibility        by jane austen
#>  9 Sense & Sensibility           jane austen
#> 10 Sense & Sensibility      jane austen 1811
#> # ... with 19,791 more rows
like image 183
alistaire Avatar answered Oct 01 '22 06:10

alistaire