How to use bigrams and trigrams using tidy text
Asked Answered
A

1

6

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
Angarsk answered 13/8, 2017 at 18:21 Comment(0)
G
13

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
Gunflint answered 13/8, 2017 at 18:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.