Take a random sample of documents of the specified size from a corpus, with or without replacement. Works just as sample works for the documents and their associated document-level variables.

corpus_sample(x, size = ndoc(x), replace = FALSE, prob = NULL,
  by = NULL, ...)

Arguments

x

a corpus object whose documents will be sampled

size

a positive number, the number of documents to select

replace

Should sampling be with replacement?

prob

A vector of probability weights for obtaining the elements of the vector being sampled. May not be applied when by is used.

by

a grouping variable for sampling. Useful for resampling sub-document units such as sentences, for instance by specifying by = "document"

...

unused

Value

A corpus object with number of documents equal to size, drawn from the corpus x. The returned corpus object will contain all of the meta-data of the original corpus, and the same document variables for the documents selected.

Examples

set.seed(2000) # sampling from a corpus summary(corpus_sample(data_corpus_inaugural, 5))
#> Corpus consisting of 5 documents: #> #> Text Types Tokens Sentences Year President FirstName #> 1833-Jackson 499 1269 29 1833 Jackson Andrew #> 1949-Truman 781 2513 116 1949 Truman Harry S. #> 1869-Grant 485 1235 40 1869 Grant Ulysses S. #> 1873-Grant 552 1475 43 1873 Grant Ulysses S. #> 1961-Kennedy 566 1566 52 1961 Kennedy John F. #> #> Source: Gerhard Peters and John T. Woolley. The American Presidency Project. #> Created: Tue Jun 13 14:51:47 2017 #> Notes: http://www.presidency.ucsb.edu/inaugurals.php
summary(corpus_sample(data_corpus_inaugural, 10, replace = TRUE))
#> Corpus consisting of 10 documents: #> #> Text Types Tokens Sentences Year President FirstName #> 1885-Cleveland 676 1820 44 1885 Cleveland Grover #> 2009-Obama 938 2711 110 2009 Obama Barack #> 1957-Eisenhower 621 1931 92 1957 Eisenhower Dwight D. #> 1977-Carter 527 1376 52 1977 Carter Jimmy #> 1929-Hoover 1090 3865 158 1929 Hoover Herbert #> 1813-Madison 541 1302 33 1813 Madison James #> 1821-Monroe 1259 4886 129 1821 Monroe James #> 1793-Washington 96 147 4 1793 Washington George #> 1805-Jefferson 804 2381 45 1805 Jefferson Thomas #> 2013-Obama 814 2317 88 2013 Obama Barack #> #> Source: Gerhard Peters and John T. Woolley. The American Presidency Project. #> Created: Tue Jun 13 14:51:47 2017 #> Notes: http://www.presidency.ucsb.edu/inaugurals.php
# sampling sentences within document corp <- corpus(c(one = "Sentence one. Sentence two. Third sentence.", two = "First sentence, doc2. Second sentence, doc2.")) corpsent <- corpus_reshape(corp, to = "sentences") texts(corpsent)
#> one.1 one.2 one.3 #> "Sentence one." "Sentence two." "Third sentence." #> two.1 two.2 #> "First sentence, doc2." "Second sentence, doc2."
texts(corpus_sample(corpsent, replace = TRUE, by = "document"))
#> one.2 one.2.1 one.2.2 #> "Sentence two." "Sentence two." "Sentence two." #> two.2 two.1 #> "Second sentence, doc2." "First sentence, doc2."