【发布时间】: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")
【问题讨论】:
-
你能显示预期的输出吗?