在R中使用print()打印换行符


111

我正在尝试在R中打印多行消息。例如,

print("File not supplied.\nUsage: ./program F=filename",quote=0)

我得到了输出

File not supplied.\nUsage: ./program F=filename

而不是期望的

File not supplied.
Usage: ./program F=filename

Answers:


130

的替代方法cat()writeLines()

> writeLines("File not supplied.\nUsage: ./program F=filename")
File not supplied.
Usage: ./program F=filename
>

一个优点是您不必记住在消息后将a 附加"\n"到传递给新cat()行的字符串。例如,将以上内容与相同的cat()输出进行比较:

> cat("File not supplied.\nUsage: ./program F=filename")
File not supplied.
Usage: ./program F=filename>

> cat("File not supplied.\nUsage: ./program F=filename","\n")
File not supplied.
Usage: ./program F=filename
>

原因print()不符合您的要求,是因为它print()显示了R级别的对象版本-在这种情况下,它是一个字符串。您需要使用其他功能,例如cat()writeLines()显示字符串。我之所以说“版本”,是因为精度可能会降低打印的数字,并且打印的对象可能会增加额外的信息。


25

你可以这样做:

cat("File not supplied.\nUsage: ./program F=filename\n")

请注意,catreturn值为NULL


3
但是不要忘记尾随的换行符。
哈德利2010年

+1 @Shane我需要cat(“ \ n”)做其他事情,看到这有帮助!谢谢
Alos 2012年

7

使用writeLines还可以使您免除“ \ n”换行符c()。如:

writeLines(c("File not supplied.","Usage: ./program F=filename",[additional text for third line]))

如果您打算编写包含固定和可变输入组合的多行消息,例如上面的[第三行的附加文本],这将很有帮助。


-1

您也可以结合使用catpaste0

cat(paste0("File not supplied.\n", "Usage: ./program F=filename"))

当将变量合并到打印输出中时,我发现这更有用。例如:

file <- "myfile.txt"
cat(paste0("File not supplied.\n", "Usage: ./program F=", file))
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.