将换行符插入字符变量

时间:2019-10-29 11:46:45

标签: r tidyverse

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

例如,我有以下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

我想创建一个包含与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")

1 个答案:

答案 0 :(得分: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"