Calling libraries required

invisible(lapply(c("knitr","xtable","reshape2","data.table", "plyr","dplyr","tm","ggplot2","DT","usmap","plotly", "stringi", "DT", "SnowballC", "RWeka", "ggplot2", "tm"), 
                 library, character.only = TRUE))

Download, extract and load data

Downloads the data, and creates the necessary subdirs, checking if the steps are already done

## Step 1: Download the dataset and unzip folder
if(!file.exists("./projectData")){
  dir.create("./projectData")
}

### Set larger timeout to download larger files
options(timeout=6000)

#### Store the download URL in a variable
Url <- "https://d396qusza40orc.cloudfront.net/dsscapstone/dataset/Coursera-SwiftKey.zip"


## Step 2: checks for file existence, then downloads it
if(!file.exists("./projectData/Coursera-SwiftKey.zip")){
  download.file(Url,destfile="./projectData/Coursera-SwiftKey.zip",mode = "wb")
}

## Step 3: downloads file
unzip(zipfile="./projectData/Coursera-SwiftKey.zip",exdir="./projectData")

Load data into dataframes

Reads the files corresponding to English texts only, and loads them into dataframes. Also fixes the encoding to avoid errors.

Descriptive summaries of the files’ contents

Builds a table with the basic summaries for the files studied.

# Step 1: Get file sizes, in MB
lineBlogs.size <- file.info("blogs.txt")$size / 1024 ^ 2
lineNews.size <- file.info("news.txt")$size / 1024 ^ 2
lineTwitter.size <- file.info("twitter.txt")$size / 1024 ^ 2

# Step 2: Get a word count inside the files
lineBlogs.words <- stri_count_words(blogs)
lineNews.words <- stri_count_words(news)
lineTwitter.words <- stri_count_words(twitter)

# Builds a summary table
dfSummary <- data.frame(source = c("blogs", "news", "twitter"),
           file.size.MB = c(lineBlogs.size, lineNews.size, lineTwitter.size),
           num.lines = c(length(blogs), length(news), length(twitter)),
           num.words = c(sum(lineBlogs.words), sum(lineNews.words), sum(lineTwitter.words)),
           mean.num.words = c(mean(lineBlogs.words), mean(lineNews.words), mean(lineTwitter.words)))

datatable(dfSummary)

Data Cleaning

A series of transformations are required to deal with special characters, punctuations, numbers, excess whitespace, stopwords, and changing the text to lower case.

Also, due to the size of the datasets, we chose to do a random sampling of the files; according to Wright (2009), for a population between 100.000 and 100.000.000, a random sample of 1067 samples, or about 1% of the mean population of the three files studies, yeld a sampling error of below 3%.

# Sets the seed to make the random sample reproducible
set.seed(1)

#Gets a random sample of words
data.sample <- c(sample(blogs, length(blogs) * 0.01),
                 sample(news, length(news) * 0.01),
                 sample(twitter, length(twitter) * 0.01))

#Function to remove URL
removeURL <- function(x) gsub("http[[:alnum:][:punct:]]*", "", x)

# Create corpus and clean the data
corpus <- VCorpus(VectorSource(data.sample))
toSpace <- content_transformer(function(x, pattern) gsub(pattern, " ", x))
corpus <- tm_map(corpus, toSpace, "(f|ht)tp(s?)://(.*)[.][a-z]+")
corpus <- tm_map(corpus, toSpace, "@[^\\s]+")
corpus <- tm_map(corpus, tolower)
corpus <- tm_map(corpus, removeWords, stopwords("en"))
corpus <- tm_map(corpus, removePunctuation)
corpus <- tm_map(corpus, removeNumbers)
corpus <- tm_map(corpus, stripWhitespace)
corpus <- tm_map(corpus, stemDocument) 
corpus <- tm_map(corpus, PlainTextDocument) 

Exploratory Analysis

The most frequent unigrams, bigrams and trigrams are found and shown for each of the 3 files studied

## Gets an additional R process to help process the calculations
options(mc.cores=1)

### Defines the function to get the word frequencies for unigrams...
getFreq <- function(tdm) {
  freq <- sort(rowSums(as.matrix(tdm)), decreasing = TRUE)
  return(data.frame(word = names(freq), freq = freq))
}
### ... bigrams...
bigram <- function(x) NGramTokenizer(x, Weka_control(min = 2, max = 2))
### ... and trigrams.
trigram <- function(x) NGramTokenizer(x, Weka_control(min = 3, max = 3))

###Defines the function to plot the histograms
makePlot <- function(data, label, color) {
  ggplot(data[1:20,], aes( y = reorder(word, freq), x = freq)) +
         labs(y = label, x = "Frequency") +
         theme(axis.text.y = element_text(size = 12, hjust = 1)) +
         geom_col(stat = "identity", fill = I(color)) 
}
# Get frequencies of most common n-grams in data sample
freq1 <- getFreq(removeSparseTerms(TermDocumentMatrix(corpus), 0.9999))
freq2 <- getFreq(removeSparseTerms(TermDocumentMatrix(corpus, control = list(tokenize = bigram)), 0.9999))
freq3 <- getFreq(removeSparseTerms(TermDocumentMatrix(corpus, control = list(tokenize = trigram)), 0.9999))

Here is a histogram of the 20 most common unigrams in the data sample.

colorUnigram = "#CC0066"
makePlot(freq1, "20 Most Common Unigrams",colorUnigram)

Here is a histogram of the 20 most common bigrams in the data sample.

colorBigram = "#333399"
makePlot(freq2, "20 Most Common Bigrams", colorBigram)

Here is a histogram of the 20 most common trigrams in the data sample.

colorTrigram = "#CC00CC"
makePlot(freq3, "20 Most Common Trigrams", colorTrigram)

Conclusion + next steps

Predictably, common words and word combinations were more prevalent, and the frequency of bigrams and trigrams is lower, making even the most common combinations relatively rare.

The predictive algorithm will perform a frequency lookup on thw bigrams and trigrams to try to predict the next word, and there will be, in the end, a shiny app with a text box where the user can type a word and the next word will be predicted.