R print() 函数
在 R 中,我们使用 print()
函数来打印值和变量。例如:
# print values
print("R is fun")
# print variables
x <- "Welcome to Programiz"
print(x)
输出
[1] "R is fun" [1] "Welcome to Programiz"
在上面的示例中,我们使用 print()
函数打印了一个字符串和一个变量。当我们在 print()
中使用变量时,它会打印存储在该变量中的值。
R 中的 paste() 函数
您还可以使用 print()
函数将字符串和变量一起打印。为此,您必须在 print()
中使用 paste()
函数。例如:
company <- "Programiz"
# print string and variable together
print(paste("Welcome to", company))
输出
Welcome to Programiz
注意在 print()
中使用 paste()
函数。paste()
函数接受两个参数:
- 字符串 - "Welcome to"
- 变量 - company
默认情况下,您可以看到字符串 Welcome to
和值 Programiz
之间有一个空格。
如果您不希望字符串和变量之间有任何默认分隔符,您可以使用 paste()
的另一个变体,称为 paste0()
。例如:
company <- "Programiz"
# using paste0() instead of paste()
print(paste0("Welcome to", company))
输出
[1] "Welcome toProgramiz"
现在,您可以看到字符串和变量之间没有空格。
R sprintf() 函数
C 语言的 sprintf()
函数也可以在 R 中使用。它用于打印格式化字符串。例如:
myString <- "Welcome to Programiz"
# print formatted string
sprintf("String: %s", myString)
输出
[1] "String: Welcome to Programiz"
这里,
String: %s
- 格式化字符串%s
- 表示字符串值的格式说明符myString
- 替换格式说明符%s
的变量
除了 %s
,还有许多其他格式说明符可用于不同类型的值。
说明符 | 值类型 |
---|---|
%c |
字符 |
%d 或 %i |
有符号十进制整数 |
%e 或 %E |
科学计数法 |
%f |
十进制浮点数 |
%u |
无符号十进制整数 |
%p |
指针地址 |
让我们在示例中使用其中一些。
# sprintf() with integer variable
myInteger <- 123
sprintf("Integer Value: %d", myInteger)
# sprintf() with float variable
myFloat <- 12.34
sprintf("Float Value: %f", myFloat)
输出
[1] "Integer Value: 123" [1] "Float Value: 12.340000"
R cat() 函数
R 编程还提供了 cat()
函数来打印变量。但是,与 print()
不同,cat()
函数仅用于基本类型,如逻辑型、整型、字符型等。
# print using Cat
cat("R Tutorials\n")
# print a variable using Cat
message <- "Programiz"
cat("Welcome to ", message)
输出
R Tutorials Welcome to Programiz
在上面的示例中,我们使用 cat()
函数显示了一个字符串和一个变量。\n
用作换行符。
注意:如前所述,您不能将 cat()
与列表或任何其他对象一起使用。
在 R 终端中打印变量
您还可以通过简单地键入变量名在 R 终端中打印变量。例如:
# inside R terminal
x = "Welcome to Programiz!"
# print value of x in console
x
// Output: [1] "Welcome to Programiz"