Skip to content

Instantly share code, notes, and snippets.

@jhollist
Created October 9, 2014 20:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhollist/6e296ad3f3b42f983d86 to your computer and use it in GitHub Desktop.
Save jhollist/6e296ad3f3b42f983d86 to your computer and use it in GitHub Desktop.
An R function to count words of an input text file. Built and tested on an Rmd without any R code in it.
word_count<-function(txt_doc){
con<-file(txt_doc, "r", blocking=FALSE)
x<-readLines(con)
#Remove YAML front matter on Rmd
if(length(grep("---",x))>0){x<-x[-seq(1,max(grep("---",x)))]}
wrds<-0
for(line in x){
#Removes non character and splits
split_line<-strsplit(gsub("[^[:alnum:] ]", "", line), " +")[[1]]
#Removes empty string
split_line<-split_line[split_line!=""]
wrds<-wrds+length(split_line)
}
return(wrds)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment