I want to create an R function that inserts a "\n" after every n words in a string (where n is an argument).
e.g.
startstring <- "I like to eat fried potatoes with gravy for dinner."
myfunction(startstring, 4)
would give:
"I like to eat\nfried potatoes with gravy\nfor dinner."
I believe that to do this I need to split the string up into several parts, each n words long, and then paste these together with a separator of "\n". However I do not know how to do the initial splitting step.
Can anyone advise?
You could solve this with regular expressions, or with this abomination:
words = strsplit(startstring, ' ')[[1L]]
splits = cut(seq_along(words), breaks = seq(0L, length(words) + 4L, by = 4L))
paste(lapply(split(words, splits), paste, collapse = ' '), collapse = '\n')
But a better way for most practical applications is to use strwrap to wrap the text at a given column length, rather than by word count:
paste(strwrap(startstring, 20), collapse = '\n')
You can use below code:
gsub("([a-z0-9]* [a-z0-9]* [a-z0-9]* [a-z0-9]*) ", "\\1\n", startstring)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With