Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R function to start new line every n words?

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?

like image 806
Mel Avatar asked Oct 24 '25 19:10

Mel


2 Answers

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')
like image 101
Konrad Rudolph Avatar answered Oct 26 '25 12:10

Konrad Rudolph


You can use below code:

gsub("([a-z0-9]* [a-z0-9]* [a-z0-9]* [a-z0-9]*) ", "\\1\n", startstring)
like image 27
Harshal Gajare Avatar answered Oct 26 '25 11:10

Harshal Gajare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!