2017-01-13 86 views
1

我有一個字符串後自動:R:自動換行功能:插入 n每16個字符

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

我想插入\ n每16個字符,包括空格後自動,以創建一個用於基本圖形繪圖的換行文本函數。

我想:

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

但這並沒有工作

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

而且是有辦法妥善分裂的話,並添加額外的空格必要在適當的自動換行功能。 謝謝你的幫助。

+7

'GSUB( 「({16})。」, 「\\ 1 \ n」,STR1)'。 – nicola

+1

相關http://stackoverflow.com/questions/34710597/justify-text-in-r – rawr

回答

1

我們可以試試這個太:

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 
+0

感謝您的偉大的解決方案。有沒有一種方法可以爲破裂的單詞添加連字符? –

+1

使用gsub替換頂部連字符的空白 –

+0

非常感謝。 –