如何用R语言单行打印

时间:2019-05-07 13:55:37

标签: r

我正在R中做一些HandOn:

toppers <- sample(80:100, 5)
s <- ifelse(toppers>90,"best class", "needs improvement")

我需要在一行中打印。我该怎么办?

实际:

[1] "best class"        "needs improvement" "needs improvement"
[4] "needs improvement" "needs improvement"

预期:

[1] "best class"        "needs improvement" "needs improvement"  "needs improvement" "needs improvement"

1 个答案:

答案 0 :(得分:2)

您的“预期”输出是不明确的,因此我将给出各种答案以涵盖所有基础。

首先,如果您只想在交互式会话中获得准确的格式,则可以简单地告诉R使用较大的行宽,以免它换行:

> options(width=9999)

调用后,默认read-eval-print循环打印的对象将显示在一行上,直到它们达到9999的长度为止。

> s
[1] "needs improvement" "needs improvement" "needs improvement" "best class"        "needs improvement"

另一种方法是仅使用cat()来将列表打印到控制台标准输出而无需任何格式。 cat()无需太多转换即可直接打印到控制台或文件。

> cat(s)
needs improvement needs improvement needs improvement best class needs improvement

您会注意到它会删除引号。如果要保留输出中每个字符串的引号,可以使用deparse()。我们还将使用sapply()分别解析每个字符串,否则它将在整个过程中放置​​不必要的c()

> cat(sapply(s, function(word) deparse(word)), collapse=' ')
"needs improvement" "needs improvement" "needs improvement" "best class" "needs improvement"

以上内容仍直接打印到控制台标准输出。如果要将合并的字符串保存在变量中,可以使用paste0()代替cat()

> x <- paste0(sapply(s, function(word) deparse(word)), collapse=' ')
> cat(x)
"needs improvement" "needs improvement" "needs improvement" "best class" "needs improvement"