Created
November 20, 2016 20:56
-
-
Save rblissett/f22bc2568fb4e9e0b6e1a4bdd6f044dc to your computer and use it in GitHub Desktop.
Two functions for wrapping strings in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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