R程序在字符串中打印新行
在本文中,我们将讨论如何使用 R 编程语言在字符串中打印新行。
方法一:使用 cat()函数
在这个方法中,需要调用cat()函数,这里负责打印文本和文本。
Syntax: cat(text/file = “”, sep = ” “, fill = FALSE, labels = NULL, append = FALSE)
Parameters:
- Text/file: text or file you want to print.
- sep: separator
- fill: If fill=TRUE, a new line will be printed if page is filled.
- labels: labels if any
R
# storing strings in variables
string1 <- "GEEKS"
string2 <- "FOR"
string3 <- "GEEKS"
# passing variable in cat() without new
# line serperator
cat(string1,string2,string3)
# passing a string using \n to split
cat("GEEKS \nFOR \nGEEKS")
# passing variables using \n
cat(string1,"\n",string2,"\n",string3)
R
# declaring variable
x <- "GEEKS \n FOR \n GEEKS"
# print x variable
writeLines(x)
# printing a string with \n new line
writeLines("GEEKS \nFOR \nGEEKS")
输出:
GEEKS FOR GEEKS
GEEKS
FOR
GEEKS
GEEKS
FOR
GEEKS
方法 2:使用 writeLines()函数
在此方法中,用户必须通过调用 writeline()函数并将其与 R 编程语言中所需的参数一起传递来使用它。
writeLines()用于在连接中写入行。
Syntax: writeLines(text, con = stdout(), sep = “\n”, useBytes = FALSE)
Parameters:
- Text: text you want to print
- con: A connection object or a character string.
- Sep: separator
- UseBytes: True/False
R
# declaring variable
x <- "GEEKS \n FOR \n GEEKS"
# print x variable
writeLines(x)
# printing a string with \n new line
writeLines("GEEKS \nFOR \nGEEKS")
输出:
GEEKS
FOR
GEEKS
GEEKS
FOR
GEEKS