[SOLVED] Add "\n" to certain elements of a string vector based on a condition


Say we have a string vector named vec. Is there a way to add "\n" before the first whole word (i.e., terms of at least two characters) of the elements of vec that exceed 10 characters?

My desired_vec is shown below.

(This is a representative toy example, but I highly appreciate for the answer to be a function.)

vec = c("Van Beuningen et al b", "bbbb & zz", "AA, BB, & CC")

desired_vec = c("Van Beuningen \net al b", "bbbb & zz", "AA, BB, & \nCC")


You can try a regular expression replace like this

gsub("^(.{9}.*?) (?=\\w{2,})(.*)", "\\1 \n\\2",vec, perl = TRUE)
# [1] "Van Beuningen \net al b" "bbbb & zz"              
# [3] "AA, BB, & \nCC"  

That will make sure you have some letters at the start, then find the first space followed by at least 2 character and then will insert a new line

Answered By – MrFlick

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *