【问题标题】:Insert linebreaks into a character-variable在字符变量中插入换行符
【发布时间】:2026-02-19 23:10:03
【问题描述】:

在 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

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

【问题讨论】:

  • 你能显示预期的输出吗?

标签: r tidyverse


【解决方案1】:

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"

【讨论】:

    最近更新 更多