You can use gsub to create an R function that inserts a \n after every n words, where n is an argument.
fun <- function(str, n) {gsub(paste0("([^ ]+( +[^ ]+){",n-1,"}) +"),
"\\1\n", str)}
fun(startstring, 4)
#[1] "I like to eat\nfried potatoes with gravy\nfor dinner."
fun(startstring, 2)
#[1] "I like\nto eat\nfried potatoes\nwith gravy\nfor dinner."
Where [^ ]+ matches everything but not a space with a length of at least one. ( +[^ ]+){3} matches at least one spache + followed by at least one not space [^ ]+ which will in this case be repeated 3 times {3}.
Or an alternative using \\K in the pattern instead of \\1 in x:
fun <- function(str, n) {gsub(paste0("[^ ]+( +[^ ]+){",n-1,"}\\K +"),
"\n", str, perl=TRUE)}
or by using strsplit:
fun2 <- function(str, n) {
paste0(strsplit(str, " +")[[1L]], c(rep(" ",n-1),"\n"), collapse = "")}
fun2(startstring, 4)
#[1] "I like to eat\nfried potatoes with gravy\nfor dinner. "
or without a space or \n in the end:
fun3 <- function(str, n) {
. <- strsplit(str, " +")[[1L]]
paste0(., c(rep_len(c(rep(" ",n-1),"\n"), length(.)-1), ""), collapse = "")}
fun3(startstring, 4)
#[1] "I like to eat\nfried potatoes with gravy\nfor dinner."
Or keeping the matched words using \K also in strsplit:
fun4 <- function(str, n) {paste(strsplit(str,
paste0("[^ ]+( +[^ ]+){",n-1,"}\\K +"), perl=TRUE)[[1L]], collapse="\n")}
fun4(startstring, 4)
#[1] "I like to eat\nfried potatoes with gravy\nfor dinner."