adam.888
adam.888

Reputation: 7846

R : wrap text function: inserting \n automatically after every 16 characters

I have a character string:

str1 <- "aaaaaaaaaa aaaaaaaaaaaaaa aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaa aaaaaaa aaa aaa"
str1
nchar(str1)

I would like to insert \n automatically after every 16 characters, including spaces, in order to create a wrap text function for use in base graphics plot.

I tried:

 str2 <- strwrap(str1, width = 16)
 str2

but this did not work

 plot(1:10,main=str2)
 mtext(str2, side=1, line=0, outer=F,cex=1,col="blue")

Also is there a way to split the words properly and add extra spaces where necessary as in a proper word wrap function. Thank you for your help.

Upvotes: 1

Views: 3199

Answers (1)

Sandipan Dey
Sandipan Dey

Reputation: 23109

We can try this too:

str2 <- paste(sapply(seq(1, nchar(str1), 16), function(i) paste0(substring(str1, i, min(i + 15, nchar(str1))), '\n')), collapse='')
str2
#[1] "aaaaaaaaaa aaaaa\naaaaaaaaa aaaaaa\naaaaaaaaaa aaaaa\naaaaaaaaaaaa aaa\naaaa aaa aaa\n"

gregexpr('\n', str2) # position of inserted newlines
#[[1]]
#[1] 17 34 51 68 81

Upvotes: 1

Related Questions