Problem Set 2

Sometimes you cannot compute the probability of an outcome by measuring the sample space and examining the symmetries of the underlying physical phenomenon, as you could do when you rolled die or picked a card from a shued deck. You have to estimate probabilities by other means. For instance, when you have to compute the probability of various english words, it is not possible to do it by examination of the sample space as it is too large. You have to resort to empirical techniques to get a good enough estimate. One such approach would be to take a large corpus of documents and from those documents, count the number of occurrences of a particular character or word and then base your estimate on that. Write a program to take a document in English and print out the estimated probabilities for each of the words that occur in that document. Your program should take in a file containing a large document and write out the probabilities of each of the words that appear in that document. Please remove all punctuation (quotes, commas, hyphens etc)and convert the words to lower case before you perform your calculations. Extend your program to calculate the probability of two words occurring adjacent to each other. It should take in a document, and two words (say the and for) and compute the probability of each of the words occurring in the document and the joint probability of both of them occurring together. The order of the two words is not important. Use the accompanying document for your testing purposes. Compare your probabilities of various words with the Time Magazine corpus: http://corpus.byu.edu/time/

require(stringr)
## Loading required package: stringr
require(dplyr)
## Loading required package: dplyr
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
sample.text <- readLines('https://raw.githubusercontent.com/komotunde/DATA605/master/assign6.sample.txt', encoding = "UFT-8") #loads our sample data from GitHub
## Warning in readLines("https://raw.githubusercontent.com/komotunde/DATA605/
## master/assign6.sample.txt", : incomplete final line found on 'https://
## raw.githubusercontent.com/komotunde/DATA605/master/assign6.sample.txt'
new.text <- gsub("[[:punct:]]"," ", sample.text) #removes all punctuation and replaces with a space

new.text <- tolower(str_replace_all(new.text, "^A-Za-z/'", " ")) #converts to all lowercase
new.text <- as.data.frame(new.text)
new.text <- sapply(new.text, function(row)iconv(row, "latin1", "ASCII", sub = " "))

Now that we have our data in with punctuation removed, we can perform our analysis.

#first  let's add a column for the percents
new.text <- as.data.frame(table(new.text))
percent.text <- new.text %>% mutate(Probability = Freq/sum(Freq)) %>% arrange(desc(Probability))

Something lookks a bit off as it appears one word occurrs the most and rest occur at the same rate of .013.

#the function will start out similar to what we did above

prob.test <- function(filename, word1, word2){prob.text <- scan(filename, character(0), encoding = "UFT-8", quote = NULL)
prob.text <- gsub("[[:punct:]]"," ", prob.text) #removes all punctuation and replaces with a space

prob.text <- tolower(str_replace_all(prob.text, "[^A-Za-z/']", " ")) #converts to all lowercase
DFprob.text <- data.frame(Word = prob.text)

DFprobtext.sort <- DFprob.text %>% group_by(Word) %>% summarize(Count = n())

DFprobtext.sort <- DFprobtext.sort %>% mutate(Prob. = Count / sum(DFprobtext.sort$Count))

DFprob.text$neighbor <- c(NA, head(prob.text, -1))
DFprob.text <- DFprob.text[2:nrow(DFprob.text),]

DFprob.text$Flag <- ifelse((DFprob.text$Word == word1 & DFprob.text$neighbor == word2) | (DFprob.text$Word == word2 & DFprob.text$neighbor == word1),1,0)

return(sum(DFprob.text$Flag)/nrow(DFprob.text))
}

Now to test our function

prob.test('file:///C:/Users/OluwakemiOmotunde/Documents/assign6.sample.txt', 'her', 'work')
## [1] 0.0007374631
#her and work have a .000737463 chance of being neighbors