在R中分成两个多字句

时间:2015-03-01 10:21:22

标签: r split

我需要以编程方式在两行一些多字句中分割/换行,说“这是一个多字句的例子”。如何用"\n"

替换最接近句子中间的空白区域

2 个答案:

答案 0 :(得分:3)

您可以使用strwrap来解决问题。

这是一个非常基本的实现:

sentSplit <- function(string, tolerance = 1.05, collapse = "\n") {
  paste(strwrap(string, width = nchar(string)/2 * tolerance), collapse = collapse)
}

sent <- "This is an example of a multi-word sentence"
sentSplit(sent)
# [1] "This is an example of\na multi-word sentence"

cat(sentSplit(sent))
# This is an example of
# a multi-word sentence

“容差”参数基本上是因为在某些情况下,它可能会将字符串拆分为3个部分,此时,您可以增加最多两个拆分的容差。

答案 1 :(得分:2)

使用strwrap()的简单解决方案:

x <- "This is an example of a multi-word sentence"

wrapInTwo <- function(x, fraction = 0.6) strwrap(x, width = fraction * nchar(x))

wrapInTwo(x)

[1] "This is an example of a" "multi-word sentence"