Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fboehm/425e6d9ea3af16c4a9ed to your computer and use it in GitHub Desktop.
Save fboehm/425e6d9ea3af16c4a9ed to your computer and use it in GitHub Desktop.
Count words and characters in Rstudio

As far as I know Rstudio does not count words or characters at the moment, which would be useful particularly when writing Rmarkdown.

This is a quick shortcut using word_count and character_count functions from qdap package. See below for two wrapper functions that simplify their use.

library("qdap")

Just select and copy the text to the clipboard and then run in the console:

Word counts

wc(readLines("clipboard", warn = FALSE))

Character counts (without spaces)

character_count(readLines("clipboard", warn = FALSE))

Character counts (with spaces)

character_count(readLines("clipboard", warn = FALSE), count.space = TRUE)

Alternatively to copying and reading text from the clipboard, one could just paste the text directly in wc or character_count functions.

Wrapper functions

These are two wrapper functions that simplify calling these functions for word and character counts:

words <- function(text){
  require(qdap)
  if (missing(text)) {
    text <- readLines("clipboard", warn = FALSE)  # read from clipboard
  }
  sum(wc(text), na.rm = TRUE)
}


chars <- function(text, spaces = FALSE){
  require(qdap)
  if (missing(text)) {
    text <- readLines("clipboard", warn = FALSE)  # read from clipboard
  }
  sum(character_count(text, count.space = spaces), na.rm = TRUE)
}

Then for counting words, use words() (after copying text to clipboard).

For counting characters (without spaces), use chars().

For counting characters (with spaces), use chars(spaces = TRUE).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment