将换行符插入字符变量

D. *_*der -1 r tidyverse

在R中将换行符插入char-Variable的最优雅方法是什么?

例如,我有以下data.frame:

longValues <- c("This is a very long text that should include linebreaks", "And also this is a very long text, that should include linereaks", "And this is an even longer text without linebreaks")
df <- data.frame(longValues)
df
Run Code Online (Sandbox Code Playgroud)

我想创建一个包含与相同值的新变量longValues,但应在一定数量的字符(比如说20)之后插入一个换行符(“ \ n”),但应在两个单词之间插入一个换行符。因此,如果单词中包含20.个字符,则换行符应位于该单词之后。

结果应该是这样的:

df$linebreaks <- c("This is a very long\n 
                 text that should include\n
                 linebreaks", 
                "And also this is a very
                long text, that should\n 
                include linereaks", 
                "And this is an even \n
                longer text without \n
                linebreaks")
Run Code Online (Sandbox Code Playgroud)

Iar*_*min 5

stringr::str_wrap 将做的工作:

library(stringr)
str_wrap(df$longValues, width = 20)

#> [1] "This is a very long\ntext that should\ninclude linebreaks"          
#> [2] "And also this is\na very long text,\nthat should include\nlinereaks"
#> [3] "And this is an even\nlonger text without\nlinebreaks"
Run Code Online (Sandbox Code Playgroud)