R函数每隔n个字开始新的一行?

问题描述 投票:1回答:1

我想创建一个R函数,在一个字符串中每隔n个字后插入一个"\n"(其中n是一个参数)。

例如,我想创建一个R函数,在字符串中每隔n个字后插入一个"\n"(其中n是参数)。

startstring <- "I like to eat fried potatoes with gravy for dinner."

myfunction(startstring, 4)

会给出。

"I like to eat\nfried potatoes with gravy\nfor dinner."

我相信要做到这一点,我需要把字符串分成几个部分,每个部分都有n个字长,然后用"\n "的分隔符把它们粘贴在一起。但是我不知道如何完成最初的分割步骤。

谁能给点建议?

r string function newline
1个回答
4
投票

你可以用正则表达式,或者用这个可恶的方法来解决。

words = strsplit(startstring, ' ')[[1L]]
splits = cut(seq_along(words), breaks = seq(0L, length(words) + 4L, by = 4L))
paste(lapply(split(words, splits), paste, collapse = ' '), collapse = '\n')

但对大多数人来说,更好的方法是 实用 应用是使用 strwrap 以给定的列长来包装文本,而不是按字数来包装。

paste(strwrap(startstring, 20), collapse = '\n')

2
投票

你可以使用下面的代码。

gsub("([a-z0-9]* [a-z0-9]* [a-z0-9]* [a-z0-9]*) ", "\\1\n", startstring)

2
投票

你可以使用 gsub 以创建一个R 功能 在每n个字后面插入一个"\n",其中n是一个参数。

fun <- function(str, n) {gsub(paste0("((\\w+ +){",n-1,"}\\w+) +")
 , "\\1\\\n", str, perl=TRUE)}
fun(startstring, 4)
#[1] "I like to eat\nfried potatoes with gravy\nfor dinner."
fun(startstring, 2)
#[1] "I like\nto eat\nfried potatoes\nwith gravy\nfor dinner."

或者使用 strsplit:

fun2 <- function(str, n) {suppressWarnings(paste(mapply(paste0
  , strsplit(str, " ")[[1]], c(rep(" ",n-1),"\n")), collapse = ""))}
fun2(startstring, 4)
#[1] "I like to eat\nfried potatoes with gravy\nfor dinner. "

1
投票

此处使用空格来分隔单词,例如: Base-R

gsub("(\\S* \\S* \\S* \\S*) ","\\1\n",startstring) 
[1] "I like to eat\nfried potatoes with gravy\nfor dinner."
© www.soinside.com 2019 - 2024. All rights reserved.