如何避免 R sprintf("very very long string with line break") 中的换行符?

How to avoid linebreak in R's sprintf("very very long string with line break")?

我里面有一个很长的字符串sprintf()。它太长了,打破它(但只在源代码中,而不是在输出中)是有用的(可读性)。但是每当我打破长字符串时,它都会引入一个 \n ,因此输出也有一个换行符。如何断开源代码中的字符串,使其在输出中不被断开?

也许像下面这样的东西会有用(尽管在不知道你的输入字符串实际是什么样子或者你打算如何使用它们的情况下很难判断)。

Fmt <- c(" %s is %d feet tall.\n", 
         "%s likes chocolate.\n",
         "%s eats %d bars of chocolate", 
         "every night after dinner.")

sprintf(paste(Fmt, collapse = " "), "Sven", 7, "Sven", "He", 3)
# [1] " Sven is 7 feet tall.\n Sven likes chocolate.\n He eats 3 bars of chocolate every night after dinner."
cat(.Last.value)
#  Sven is 7 feet tall.
#  Sven likes chocolate.
#  He eats 3 bars of chocolate every night after dinner.

使用gsub()进行相关替换,例如,将连续出现2次或多次的'space'个字符(包括换行符)替换为单个space

> sprintf("string: %s", gsub("[[:space:]]{2,}", " ", "a very
+   long
+   string"))
[1] "string: a very long string"

使用@Martin 给出的概念,但方式略有不同。

> sprintf(gsub("[[:space:]]{2,}"," ","
+         %s is %d feet tall.
+              %s likes chocolate.
+              %s eats %d bars of chocolate 
+              every night after dinner."), "Sven", 7, "Sven", "He", 3)
[1] " Sven is 7 feet tall. Sven likes chocolate. He eats 3 bars of chocolate every night after dinner."
>