How to Create Cross-Validation Partitions with Plain Text in R?

In my last blog post, I talked about Random Sampling for Plain Text in R. Now when you are performing some supervised learning on your data, if you follow the cross-validation principle which divides the data into train, holdout and test, you want to make sure each subset is different. The great caret package has some neat partitioning techniques however for my use, I wanted a minimal function without the need to load extra libraries.

createPartition <- function (filename, trainPortion=0.6, holdOutPortion=0.2) {  
  con <- file(filename)
  total <- length(readLines(con))

  sample <- floor(total * trainPortion)
  sample_holdout <- floor(total * holdOutPortion)

  corpus <- scan(con, what="character", skip= 0, nlines=total, sep="\n", fileEncoding = 'UTF-8')
  train <- corpus[1:sample]
  holdout <- corpus[(sample + 1): (sample + sample_holdout)]
  test <- corpus[(sample + sample_holdout + 1) : total]

  result <- list(train=train, holdout=holdout, test=test)

What you need to pass is only a path to filename. I set the partitions to be 60/20/20 rule which is suggested by the great Andrew Ng.

Here's how to use it:

data <- createPartition("path_to_file.format")  

I hope this helped! 😀😀😀

The Rstats tag of this blog is added to R Bloggers