Skip to content

Instantly share code, notes, and snippets.

@rblissett
Created November 20, 2016 20:56
Show Gist options
  • Save rblissett/f22bc2568fb4e9e0b6e1a4bdd6f044dc to your computer and use it in GitHub Desktop.
Save rblissett/f22bc2568fb4e9e0b6e1a4bdd6f044dc to your computer and use it in GitHub Desktop.
Two functions for wrapping strings in R
# String wrapping for a set of strings
wrap_strings <- function(vector_of_strings,width){
sapply(vector_of_strings,FUN=function(x) {paste(wrap_sentence(x,width=width))})
}
# Wraps a single sentence
wrap_sentence <- function(string, width) {
words <- unlist(strsplit(string, " "))
fullsentence <- ""
checklen <- ""
for(i in 1:length(words)) {
checklen <- paste(checklen, words[i])
if(nchar(checklen)>(width+1)) {
fullsentence <- paste0(fullsentence, "\n")
checklen <- ""
}
fullsentence <- paste(fullsentence, words[i])
}
fullsentence <- sub("^\\s", "", fullsentence)
fullsentence <- gsub("\n ", "\n", fullsentence)
return(fullsentence)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment